Oracle: Custome auto-increment: C0001 C0002 - oracle11g

i am trying to create a table in Oracle sql.
I have no trouble creating the table and the sequence i created works fine.
Right now i can use form to dial in name and email and the table will create the PK for me.
The PK ID would looked like this:
10001 | xxx | xxxx
10002 | xxx | xxxx
10003 | xxx | xxxx
My question is, how can i use function or trigger to auto update my ID, make it into:
QWER10001 | xxx | xxxx
QWER10002 | xxx | xxxx
QWER10003 | xxx | xxxx
I know how to update it manually, but i want it can put that custom text in front of my ID when i put in information.
the text can be set, no need to change it when the number reach max.
I spend hours looking for solution but can't find the right one, please help!
I also did some more research online, right now i have this:
CREATE OR REPLACE TRIGGER "PROFILE_T1"
BEFORE INSERT OR UPDATE
ON "PROFILE"
FOR EACH ROW
BEGIN
:NEW.PROFILEID := 'WCCU' sequence.PROFILEIDUSE
END;
but this did not work. PROFILEID is the PK and is auto incremented. PROFILEIDUSE is the sequence to make it auto increment. WCCU is the text i want to add to the PK when every data is entered.

create or replace trigger "PROFILE_T1"
BEFORE
insert on "PROFILE"
for each row
begin
:new.PROFILEID := 'WCCU' || PROFILEIDUSE.nextval;
end;

Since you have already created the sequence, you simply have to use it in your INSERT statement where you should explicitly specify the column value. If you don't want to explicitly specify the value in the insert statement, you can use a before inert trigger to set the value for the column.
In INSERT statement
insert into your_table values('QWER'||your_sequence.nextval,....);
Using TRIGGER
CREATE OR REPLACE TRIGGER your_trigger
BEFORE INSERT ON your_table
FOR EACH ROW
DECLARE
BEGIN
:new.your_primary_key_column := 'QWER' || your_sequence.nextval;
END your_trigger;
Now, you can exclude this primary column from your insert statement. Trigger will add it for you.

Related

How could you get if a table is autoincrement or not from the metadata of an sqlite table?

In case you have several tables inside any sqlite database how could the get the information that they have an auto increment primary key or not?
For instance I am already aware that you could get some info concerning the columns of a table by simply querying this: pragma table_info(tablename_in_here)
It would be much better to get the auto increment column dynamically rather than setting up each corresponding model inside the source code with a boolean value.
Edit:
Let me use this table as an example:
CREATE TABLE "test" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"name" TEXT NOT NULL
)
and this is the result table after executing pragma table_info("test")
cid | name | type | notnull | dflt_value | pk
0 | id | INTEGER | 1 | null | 1
1 | name | TEXT | 1 | null | 0
As you can see there is no information whether the id column is autoincrement or not
Edit2:
I looking for a solution that involves sqlite directly through a statement.
Special situations where the sqlite3 command in the terminal can be used to somehow parse the required information from inside are not acceptable. They do not work in situations where you are not allowed to execute commands in a terminal programmatically. Like in an Android app.
Autoincrementing primary keys must be declared as INTEGER PRIMARY KEY or some equivalent, so you can use the table_info date to detect them.
A column is an INTEGER PRIMARY KEY column if, in the PRAGMA table_info output,
the type is integer or INTEGER or any other case-insensitive variant; and
pk is set; and
pk is not set for any other column.
To check whether the column definition includes the AUTOINCREMENT keyword, you have to look directly into the sqlite_master table; SQLite has no other mechanism to access this information.
If this query returns a record, you have the AUTOINCREMENT keyword somewhere in the table definition (which might return a wrong result if this word is commented out):
SELECT 1
FROM sqlite_master
WHERE type = 'table'
AND name = 'tablename_in_here'
AND sql LIKE '%AUTOINCREMENT%'
You can parse the output of .schema. That will give you the sql commands as you used them to create your tables. If autoincrement was declared, you will see it in the output. This has the advantage that it will list all your tables too.

Insert only if id doesn't exist

Alright, so we have a phonegap app with a table setup like
tblTest (actualid INTEGER PRIMARY KEY, id INTEGER, name TEXT)
The actualid is a unique id for the device and the id is maintained in a server side database. We've had issues with webservices returning duplicate records and while we're fixing that I wanted to add something to our sql that would prevent duplicates from being added (fixing bad data is a pain).
Our current insert statement is setup like
INSERT INTO tblTest (id, name) VALUES (101, 'Bob')
If you run that twice the database will end up looking like
actualid | id| name
1 | 101| Bob
2 | 101| Bob
And what I'd like for it to look like is
actualid | id| name
1 | 101| Bob
Insert or Replace would give me an actualid 2 in the example and any example I've found using a where clause was setup like
INSERT INTO tblTest SELECT ..... WHERE.....
Which doesn't work because none of the data is in a table yet (unless I'm making a newbie mistake, I'm not very good at sqlite or general sql).
Use INSERT OR IGNORE:
INSERT OR IGNORE INTO tblTest (id, name) VALUES (101, 'Bob')
(This requires a unique index on the id column, which you already have.)
You might want to try this:
INSERT INTO tblTest
(id, name)
SELECT 101 as id, 'Bob' as name
FROM tblTest
WHERE NOT EXISTS(SELECT * FROM tblTest WHERE id = 101 and name = 'Bob')

how to relate two table by after insert trigger in sql server 2008r2

I am trying to create a trigger such that if i am inserting some values in 1st table than the two field of the 2nd table automatically updated.
case is that i have a table in which i'm storing user details
First Table
1st name | last name | userId | password | adress | email
and 2nd login table which have two field
Second Table
userId | password
now i want if i change value of password in 1st table is automatically reflect in the 2nd table what is the query for that.
as long as the userid and password for the second table are mapped as foreign keys to the first table, i think you should be able to set "on update cascade" on the rows
you can do like this....
CREATE TRIGGER trgTest ON Test
FOR INSERT
AS
INSERT Test2
(Id, value)
SELECT Id, Value
FROM Inserted
or if you're using stored procedures you can easily manage this
CREATE PROCEDURE sp_Insert
#Value varchar(10)
AS
insert into table1 (...,...) values (#value,...)
insert into table2 (...,...) values (#value,...)
You've mostly answered your own question, Prakash. Check out the MSDN documentation on triggers for the specific syntax you need. Jon's comment in regard to the duplication of data points out that your schema is somewhat denormalized so you may want to take a look at changing that unless it's required for your situation.
From MSDN
INSERT INTO auditEmployeeData
(audit_log_type,
audit_emp_id,
audit_emp_bankAccountNumber,
audit_emp_salary,
audit_emp_SSN)
SELECT 'NEW',
ins.emp_id,
ins.emp_bankAccountNumber,
ins.emp_salary,
ins.emp_SSN
FROM inserted ins

Save row's position without a positioning column in SQL Server 2005

Here is the table structure:
Id | Description
1 | Test1
2 | Test2
In asp.net forms, I have two fields for inserting values for this table.
As I can't add a new column for memorizing the position of rows, do you have any ideas for accomplishing this functionality?
Edit:
I don't know whether stored procedure can do this or not.
Well you could just append the order value as a suffix in the description, and when you read out the value you would remove the suffix when displaying it.
If your order is "Test2","Test1","Test3":
Id | Description
1 | Test1-2
2 | Test2-1
3 | Test3-3
Of course this is a horrible hack and you should rather add another column in your db table. But if you are unable to do this, this is the only solution I see.

What's the best way to retrieve this data?

The architecture for this scenario is as follows:
I have a table of items and several tables of forms. Rather than having the forms own the items, the items own the forms. This is because one item can be on several forms (although only one of each type, but not necessarily on any). The forms and items are all tied together by a common OrderId. This can be represented like so:
OrderItems | Form A | Form B etc....
---------- |--------- |
ItemId |FormAId |
OrderId |OrderId |
FormAId |SomeField |
FormBId |OtherVar |
FormCId |etc...
This works just fine for these forms. However, there is another form, (say, FormX) which cannot have an OrderId because it consists of items from multiple orders. OrderItems does contain a column for FormXId as well, but I'm confused about the best way to get a list of the "FormX"s related to a single OrderId. I'm using MySQL and was thinking maybe a stored proc was the best way to go on this, but I've never used a stored proc on MySQL and don't really know the best way to go about it. My other (kludgy) option was to hit the DB twice, first to get all the items that are for the given OrderId that also have a FormXId, and then get all their FormXIds and do a dynamic SELECT statement where I do something like (pseudocode)
SELECT whatever FROM sometable WHERE FormXId=x OR FormXId=y....
Obviously this is less than ideal, but I can't really think of any other way... anything better I could do either programmatically or architecturally? My back-end code is ASP.NET.
Thanks so much!
UPDATE
In response to the request for more info:
Sample input:
OrderId = 1000
Sample output
FormXs:
-----------------
FormXId | FieldA | FieldB | etc
-------------------------------
1003 | value | value | ...
1020 | ... .. ..
1234 | .. . .. . . ...
You see the problem is that FormX doesn't have one single OrderId but is rather a collection of OrderIds. Sometimes multiple items from the same order are on FormX, sometimes it's just one, most orders don't have any items on FormX. But when someone pulls up their order, I need for all the FormXs their items belong on to show up so they can be modified/viewed.
I was thinking of maybe creating a stored proc that does what I said above, run one query to pull down all the related OrderIds and then another to return the appropriate FormXs. But there has to be a better way...
I understand you need to get a list of the "FormX"s related to a single OrderId. You say, that OrderItems does contain a column for FormXId.
You can issue the following query:
select
FormX.*
From
OrderItems
join
Formx
on
OrderItems.FormXId = FormX.FormXId
where
OrderItems.OrderId = #orderId
You need to pass #orderId to your query and you will get a record set with FormX records related to this order.
You can either package this query up as a stored procedure using #orderId paramter, or you can use dynamic sql and substitute #orderId with real order number you executing your query for.

Resources