How to get sequence start value from another table's max value - sql

I'm trying to insert a bunch of values in a table but it doesn't have IDENTITY column, and I need to insert a unique value in that field.
And the sequential number should be start based on the previous value present in that same field.
lets say I have a table like this
create table testTable (id int, fieldA varchar (20))
insert into testTable
values (6,'Nick'),(7,'Tom')
Now the next value I insert in ID field should take be 8 and next row should be 9 and so on...
And below is the sequence I created; and is not working
CREATE SEQUENCE testTable_seq
declare #maxy int = ((select max(ID) from testTable) + 1)
START WITH #maxy
INCREMENT BY 1
I expect the below insert should get the next value from the sequence I created or just tto get the next sequential number from previous ID field
insert into testTable
values (testTable_seq.next value,'Harry')

You can't do that, if you see the arguments in the docs CREATE SEQUENCE it already stated that the value of START WITH should be a constant value, same as INCREMENT BY, MINVALUE and MAXVALUE
START WITH constant
I don't understand why you want to create a SEQUENCE to insert values into a table, and also MAX() won't do as you expect, instead you can simply
CREATE TABLE TestTable(
ID INT IDENTITY(1, 1) NOT NULL,
AColumn VARCHAR(20),
CONSTRAINT PK_TestTable_ID PRIMARY KEY(ID)
);

Related

Having troubles with Identity field of SQL-SERVER

I'm doing a school project about a school theme where I need to create some tables for Students, Classes, Programmes...
I want to add a Group to determined classes with an auto increment in group_id however I wanted the group_id variable to reset if I change any of those attributes(Classes_id,courses_acronym,year_Semesters) how can I reset it every time any of those change??
Here is my table:
CREATE TABLE Classes_Groups(
Classes_id varchar(2),
Group_id INT IDENTITY(1,1),
courses_acronym varchar(4),
year_Semesters varchar(5),
FOREIGN KEY (Classes_id, year_Semesters,courses_acronym) REFERENCES Classes(id,year_Semesters, courses_acronym),
PRIMARY KEY(Classes_id,courses_acronym,year_Semesters,Group_id)
);
Normally, you do not (need to) reset the identity column of a table. An identity column is used to create unique values for every single record in a table.
So you want to generate entries in your groups table based on new entries in your classes table. You might create a trigger on your classes table for that purpose.
Since Group_id is already unique by itself (because of its IDENTITY), you do not need other fields in the primary key at all. Instead, you may create a separate UNIQUE constraint for the combination (Classes_id, courses_acronym, year_Semesters) if you need it.
And if the id field of your classes table is an IDENTITY column too, you could define a primary key in your classes table solely on that id field. And then your foreign key constraint in your new groups table can only include that Classes_id field.)
So much for now. I guess that your database design needs some more additional tuning and tweaking. ;)
where are you setting the values from?, you can have a stored proc and in your query have the columns have an initial value set when stored proc is hit assuming there are values at the beginning
.Then use an IF statement.
declare #initial_Classes_id varchar(2) = --initial value inserted
declare #initial_courses_acronym varchar(4) = --initial value inserted
declare #initial_year_Semesters varchar(5) = --initial value inserted
declare #compare_Classes_id varchar(2) = (select top 1 Classes_id from Classes_Groups order by --PK column desc for last insert); l would add Dateadded and then order with last insert date
declare #compare_courses_acronym varchar(2) = (select top 1 Classes_id from Classes_Groups where Classes_id = #compare_Classes_id);
declare #compare_year_Semesters varchar(2) = (select top 1 Classes_id from Classes_Groups where Classes_id = #compare_Classes_id);
IF (#initial_Classes_id != #compare_Classes_id OR #initial_courses_acronym != #compare_courses_acronym OR #initial_year_Semesters != #compare_year_Semesters)
BEGIN
DBCC CHECKIDENT ('Group_id', RESEED, 1)
Insert into Classes_Groups (courses_acronym,year_Semesters)
values (
courses_acronym,
year_Semesters
)
END
ELSE
BEGIN
Insert into Classes_Groups (courses_acronym,year_Semesters)
values (
courses_acronym,
year_Semesters
)
END
NB: would advice to use int on the primary key. Unless you have a specific purpose of doing so.

Two identity columns in SQL Server 2008

I am creating a table in SQL Server with three columns. I want the first two columns to increment counts one by one. I used the first column as identity column that automatically increments 1 when row is inserted. I tried to do the same with second column (but SQL Server does not allow two identity columns per table). I found another way i-e using Sequence but since I am using SQL Server 2008, it does not have this feature.
How can I achieve my task?
I am using the first identity column in reports and I reset it when some count is achieved; for example when it reaches 20, I reset it to 1 (Edited). The second incremental column will be used by me for sorting the data and i do not intend to reset it.
create table tblPersons
(
IDCol int primary key identity(1,1),
SortCol int primary key identity(1,1),
Name nvarchar(50)
)
PS : I cannot copy the values of IDCol to SortCol because when I reset the IDCol to 20 from my code, the SortCol will copy the same values (instead it should continue to 21,22,23 and so on)
If you plan on incrementing both columns always at the same time, then one workaround here might be to just use a single auto increment column, but use the remainder of that counter divided by 20 for the second value:
CREATE TABLE tblPersons (
IDCol int PRIMARY KEY IDENTITY(1,1),
Name nvarchar(50)
)
SELECT
IDCol,
IDCol % 20 AS SortCol -- this "resets" to zero upon reaching 20
FROM tblPersons;
As an alternative solution, you can use Computed Column
create table tblPersons
(
SortCol int primary key identity(1,1),
IDCol AS CASE WHEN (SortCol % 20) = 0 THEN 20 ELSE (SortCol % 20) END ,
Name nvarchar(50)
)

Add Row number to a new column

I want to create a new column and populate the value of each row in that column with the row number.
This could be achieved in oracle by doing this.
alter table mytable add (myfield integer);
update mytable set myfield = rownum;
How would this be done in SYBASE ASE?
alter table mytable
add id bigint identity not null
That's all. There will be a column id in every row that contains a unique sequence number for that row.
create column table some_names
(ID bigint not null primary key generated by default as IDENTITY,
NAME nvarchar(30));
And now we can do things like this:
insert into some_names (name) values ('Huey');
insert into some_names (name) values ('Dewey');
insert into some_names (name) values ('Louie');
In my case when I tried to do it with identity column time it wasn't able to finish in reasonable time (196400 rows).
Fast and easy way was to create an INT column and fill it up using a temporary variable #id incremented after each row.
This solution finished in ~4 seconds.
alter mytable add myfield INT
DECLARE #id INT
SET #id = 0
UPDATE mytable
SET #id = myfield = #id + 1
You can find more info here: https://www.mssqltips.com/sqlservertip/1467/populate-a-sql-server-column-with-a-sequential-number-not-using-an-identity/

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
)

Postgres: Problems using insert with select

I have a table defined like this:
CREATE TABLE wp_master (
gid integer NOT NULL DEFAULT nextval('wp_master_gid_seq'::regclass),
name character varying(80),
....
type integer DEFAULT 4,
CONSTRAINT p_key PRIMARY KEY (gid),
);
I want to insert data into the table from another table so I
insert into wp_master ( name, .... type) select "NAME", ...., 1 from ."Tiri2011";
but I get the error:
ERROR: duplicate key value violates unique constraint "p_key"
DETAIL: Key (gid)=(2) already exists.
Why is postgres trying to put anything into the gid field when I have explicitly not included it in the list of columns? I assumed that gid pick up its value from the sequence.
Russell
Is is trying to insert the next value of the wp_master_gid_seq sequence. Declaring an id column as serial (auto-increment) will create a sequence which has a stored value of the last inserted id which was auto-incremented. If at anytime you inserted a gid value manually, it bypassed the sequence and the autoincrement function may become broken, because the sequence value did not get updated accordingly.
The easiest way to fix it is to change the value of the sequence to the (max gid value of your table) + 1. Just execute this once and you should be ok
select setval('wp_master_gid_seq', coalesce((select max(id)+1 from wp_master), 1), false)