HSQLDB - link several sequences for several columns of the table - sql

I would like to link several sequences for generating default values for several columns of a table.
For example:
CREATE SEQUENCE seq1 START WITH 1;
CREATE SEQUENCE seq2 START WITH 1;
CREATE TABLE mytable (rid int GENERATED BY DEFAULT AS SEQUENCE seq1 PRIMARY KEY, p63 int GENERATED BY DEFAULT AS SEQUENCE seq2)
Unfortunately, an error is occured: "identity definition not allowed"
In Postgresql is working.
Any idea ?
Thanks

The first use of the sequence is allowed. You can write a BEFORE INSERT TRIGGER to insert sequence values into the second column.

Having the same issue, I came upon this post. I used another workaround :
CREATE SEQUENCE seq1 START WITH 1;
CREATE SEQUENCE seq2 START WITH 1;
CREATE TABLE mytable (
rid int DEFAULT nextval('seq1') NOT NULL,
p63 int NOT NULL
);
ALTER TABLE mytable ALTER p63 SET DEFAULT NEXTVAL('seq2');
Altering the p63 column after table creation made possible to use the seq2 sequence while it was not accepted when creating the table.

Related

Does postgres support to set start value at serial definition?

Here is a question about changing serial value with alter key word. Can this be done in create table defintion? Like that:
CREATE TABLE tablename (
colname SERIAL stars 1000
);
You can try this query.Its worked for me.
CREATE SEQUENCE tablename_colname_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1 ---> here you can mention startup nummber as you need
CACHE 1;
CREATE TABLE tablename (
colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
Identity Columns
There is no currently no way to do this in a CREATE TABLE command in PostgreSQL 9.x using the PostgreSQL-specific serial-type syntax. However, it's coming in PostgreSQL 10 using the standardized Identity Columns syntax, see my answer on it here
Here is how it will look
CREATE TABLE foo (
id int GENERATED { ALWAYS | BY DEFAULT }
AS IDENTITY [ ( sequence_options ) ]
);
Where (sequence_options) is START WITH 1000, so something like this.
CREATE TABLE foo (
foo_id int GENERATED ALWAYS AS IDENTITY (START WITH 1000)
);

SQL Primary Key Increment

How can I have a primary key that auto increments?
for example: when I insert something at the field name, the field id should be assign a value that is +1 that the last one.
id, name
1, test1
2, test2
so I insert the name something like testX and the id should be auto assigned as 3
how can i do that?
In addition to answer of ain, you can use generator like :
Create a generator :
CREATE GENERATOR <name>;
SET GENERATOR <name> TO <value>;
Getting the current value of generator:
SELECT GEN_ID( <GeneratorName>, 0 ) FROM RDB$DATABASE;
Generating the next value
SELECT GEN_ID( <GeneratorName>, 1 ) FROM RDB$DATABASE;
Using generator in trigger
CREATE OR ALTER trigger <trigger_name>_bi for <table_name>
active before insert position 0
as
begin
if (new.id is null) then
new.id = gen_id(my_generator,1);
end
If you want numeration without holes you have to be very careful.
Generators/Sequences are non-transactional.
Once you get a value if your operation fails, you will have a hole.
If you're using Firebird 3 then you can use the identity column feature:
create table T (
id integer generated by default as identity primary key,
...
);
If you're using some older version of Firebird, then using an sequence with trigger can be used to achieve the autoincrement:
create table T (
id integer primary key,
...
);
CREATE SEQUENCE t_seq;
create trigger t_gen_id
active before insert
on T
as
begin
if(new.id is null)then new.id = next value for t_seq;
end;
Since Firebird 2 the returning clause is supported which is very handy to get the id value generated on the server side.

SQL Server Database unique number generation on any record insertion

I have like 11 columns in my database table and i am inserting data in 10 of them. i want to have a unique number like "1101 and so on" in the 11th column.
Any idea what should i do?? Thanks in advance.
SQL Server 2012 and above you can generate Sequence
Create SEQUENCE RandomSeq
start with 1001
increment by 1
Go
Insert into YourTable(Id,col1...)
Select NEXT VALUE FOR RandomSeq,col1....
or else you can use Identity
Identity(seed,increment)
You can start the seed from 1101 and increment the sequence by 1
Create table YourTable
(
id INT IDENTITY(1101,1),
Col varchar(10)
)
If you want to have that unique number in a different field then you can manipulate that field with primary key and insert that value.
If you want in primary key value, then open the table in design mode, go to 'Identity specification', set 'identity increment' and 'identity seed' as you want.
Alternatively you can use table script like,
CREATE TABLE Persons
(
ID int IDENTITY(12,1) PRIMARY KEY,
FName varchar(255) NOT NULL,
)
here the primary key will start seeding from 12 and seed value will be 1.
If you have your table definition already in place you can alter the column and add Computed column marked as persisted as:
ALTER TABLE tablename drop column column11;
ALTER TABLE tablename add column11 as '11'
+right('000000'+cast(ID as varchar(10)), 2) PERSISTED ;
--You can change the right operator value from 2 to any as per the requirements.
--Also replace ID with the identity column in your table.
create table inc
(
id int identity(1100,1),
somec char
)

How to add a sequence column to an existing table with records

I had created a new table named USERLOG with two fields from a previous VIEW. The table already consist of about 9000 records. The two fields taken from the VIEW, i.e. weblog_views consist of IP (consists of IP address), and WEB_LINK (consists of URL). This is the code I used,
CREATE TABLE USERLOG
AS
SELECT C_IP, WEB_LINK FROM weblog_views;
I want to add another column to this table called the USER_ID, which would consists of a sequence starting with 1 to 9000 records to create a unique id for each existing rows. I need help with this part. I'm using Oracle SQL Developer: ODMiner version 3.0.04.
I tried using the AUTO-INCREMENT option,
ALTER TABLE USERLOG
ADD USER_ID INT UNSIGNED NOT NULL AUTO_INCREMENT;
But I get an error with this,
Error report:
SQL Error: ORA-01735: invalid ALTER TABLE option
01735. 00000 - "invalid ALTER TABLE option"
So, I would really appreciate any help that I can get!
You would need to add a column
ALTER TABLE userlog
ADD( user_id number );
create a sequence
CREATE SEQUENCE user_id_seq
START WITH 1
INCREMENT BY 1
CACHE 20;
Update the data in the table
UPDATE userlog
SET user_id = user_id_seq.nextval
Assuming that you want user_id to be the primary key, you would then add the primary key constraint
ALTER TABLE userlog
ADD CONSTRAINT pk_user_id PRIMARY KEY( user_id );
If you want to use the sequence to automatically add the user_id when you do an INSERT (the other option would be to specifically reference user_id_seq.nextval in your INSERT statements, you would also need a trigger
CREATE OR REPLACE TRIGGER trg_userlog_user_id
BEFORE INSERT ON userlog
FOR EACH ROW
BEGIN
:new.user_id := user_id_seq.nextval;
END;
In addition to Justin's excellent answer you might want to prevent NULL values for your user_id in the future (as they could still be caused by UPDATE statements). Therefore, execute the following statement at the end:
ALTER TABLE userlog MODIFY(user_id number NOT NULL);
Step 1.
Create sequence to be used by the column
eg:
CREATE SEQUENCE user_id_seq
START WITH 1
INCREMENT BY 1
CACHE 20;
Step 2.
Update new column with sequence
eg:
UPDATE userlog
SET user_id = user_id_seq.nextval;
Step 3. - Set Sequence as the default value for the column, will work only above Oracle 12c
ALTER TABLE USERLOG
MODIFY USER_ID INT DEFAULT user_id_seq.nextval;

Can a sql server table have two identity columns?

I need to have one column as the primary key and another to auto increment an order number field. Is this possible?
EDIT: I think I'll just use a composite number as the order number. Thanks anyways.
CREATE TABLE [dbo].[Foo](
[FooId] [int] IDENTITY(1,1) NOT NULL,
[BarId] [int] IDENTITY(1,1) NOT NULL
)
returns
Msg 2744, Level 16, State 2, Line 1
Multiple identity columns specified for table 'Foo'. Only one identity column per table is allowed.
So, no, you can't have two identity columns. You can of course make the primary key not auto increment (identity).
Edit: msdn:CREATE TABLE (Transact-SQL) and CREATE TABLE (SQL Server 2000):
Only one identity column can be created per table.
You can use Sequence for second column with default value IF you use SQL Server 2012
--Create the Test schema
CREATE SCHEMA Test ;
GO
-- Create a sequence
CREATE SEQUENCE Test.SORT_ID_seq
START WITH 1
INCREMENT BY 1 ;
GO
-- Create a table
CREATE TABLE Test.Foo
(PK_ID int IDENTITY (1,1) PRIMARY KEY,
SORT_ID int not null DEFAULT (NEXT VALUE FOR Test.SORT_ID_seq));
GO
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
INSERT INTO Test.Foo VALUES ( DEFAULT )
SELECT * FROM Test.Foo
-- Cleanup
--DROP TABLE Test.Foo
--DROP SEQUENCE Test.SORT_ID_seq
--DROP SCHEMA Test
http://technet.microsoft.com/en-us/library/ff878058.aspx
Add one identity column and then add a computed column whose formula is the name of the identity column
Now both will increment at the same time
No it is not possible to have more than one identity column.
The Enterprise Manager does not even allow you to set > 1 column as identity. When a second column is made identity
Also note that ##identity returns the last identity value for the open connection which would be meaningless if more than one identity column was possible for a table.
create table #tblStudent
(
ID int primary key identity(1,1),
Number UNIQUEIDENTIFIER DEFAULT NEWID(),
Name nvarchar(50)
)
Two identity column is not possible but if you accept to use a unique identifier column then this code does the same job as well. And also you need an extra column - Name column- for inserting values.
Example usage:
insert into #tblStudent(Name) values('Ali')
select * from #tblStudent
Ps: NewID() function creates a unique value of type uniqueidentifier.
The primary key doesn't need to be an identity column.
You can't have two Identity columns.
You could get something close to what you want with a trigger...
in sql server it's not possible to have more than one column as identity.
I've just created a code that will allow you inserting two identities on the same table. let me share it with you in case it helps:
create trigger UpdateSecondTableIdentity
On TableName For INSERT
as
update TableName
set SecondIdentityColumn = 1000000+##IDENTITY
where ForstId = ##IDENTITY;
Thanks,
A workaround would be to create an INSERT Trigger that increments a counter.
So I have a table that has one identity col : applicationstatusid. its also the primary key.
I want to auto increment another col: applicationnumber
So this is the trigger I write.
create trigger [applicationstatus_insert] on [ApplicationStatus] after insert as
update [Applicationstatus]
set [Applicationstatus].applicationnumber =(applicationstatusid+ 4000000)
from [Applicationstatus]
inner join inserted on [applicationstatus].applicationstatusid = inserted.applicationstatusid