Reset INCREMENT VALUE For Identity Column using T-SQL Script - sql

I Need Change Increment Value for Identity Column
For Example
I have create table Test Table with Identity Column
Create Table test
(
Id Int Identity(1,1)
,Name Varchar(200)
)
Now it is easy to Reseed the start value of Identity Column using
DBCC CheckIdent('TEST',Reseed,100)
But I want to change the Increment value 1 to 10
is there any sql command that will work ..
While changing from SSMS 2016 I get this error

To change the increment you need to drop the existing identity() column and add a new column.
alter table test drop column Id;
alter table test add Id int identity(100,10);
If you want to keep existing values, then you will need to create a new table, insert the existing rows with identity_insert on, drop the old table, and rename the new table.
For example:
create table test (id int identity(1,1), name varchar(200) default '')
insert into test default values
insert into test default values
create table new_test (id int identity(100,10), name varchar(200) default '');
set identity_insert new_test on;
insert into new_test (id,name)
select id,name from test
set identity_insert new_test off;
drop table test;
exec sp_rename 'new_test','test';
insert into test default values;
insert into test default values;
select * from test;
rextester demo: http://rextester.com/XDE9355
returns:
+-----+------+
| id | name |
+-----+------+
| 1 | |
| 2 | |
| 100 | |
| 110 | |
+-----+------+

Related

Postgres - Add a column to a table with a default value, but set existing rows to a different default value

I want to add a boolean column to a table and have the default value be false for newly created rows, but all existing rows should be set to true. How can I do that?
First alter table and add column as
alter table table_name add column column_name boolean default false;
Then update value of that column as
update table_name set column_name=true;
A simplified test to demonstrate.
create table test (
id int primary key
);
insert into test (id) values (1), (2), (3);
alter table test
add column truth boolean default false;
update test set truth = true;
insert into test (id) values (4), (5);
select * from test;
id | truth
-: | :----
1 | t
2 | t
3 | t
4 | f
5 | f
db<>fiddle here

Generate unique IDs in non-unique columns

Consider this table:
ex_table
| gid | val |
| --- | --- |
| 1 | v1 |
| 1 | v2 |
| 2 | v3 |
Notice that gid is the id-like column and not unique.
I want to be able to insert values into the table either by generating a unique gid or by specifying which one to use.
For example:
INSERT INTO ex_table (val)
SELECT --....
Should generate a unique gid, while
INSERT INTO ex_table (gid, val)
SELECT --....
Should use the provided gid.
Any way to do this?
You can do what you want to the letter of what you say by using overriding system value and an auto-generated column. For instance:
create table t (
gid int generated always as identity,
name varchar(255)
);
Then
insert into t (name) values ('abc');
insert into t (gid, name) overriding system value values (1, 'def')
will insert two rows with a gid value of 1.
Here is an example.
Just one caveat: Inserting your own value does not change the next value that is automatically generated. So, if you manually insert values that do not exist, then you might find that duplicates are later generated for them.
You can try something like this
CREATE SEQUENCE table_name_id_seq;
CREATE TABLE table_name (
gid integer NOT NULL DEFAULT nextval('table_name_id_seq'),
name varchar);
ALTER SEQUENCE table_name_id_seq
OWNED BY table_name.id;
OR SIMPLY
CREATE TABLE table_name(
gid SERIAL,
name varchar);
AND THEN TO INSERT
INSERT INTO fruits(gid,name)
VALUES(DEFAULT,'Apple');

SQL Identity(1,1) as a Default constrain

I'm trying to define a new table as follows and I want the IndexPosition column to get the MAX(IndexPosition) + 1 by default.
CREATE TABLE SpeechOutputList
(ID int NOT NULL IDENTITY(1,1),
IndexPosition int DEFAULT (???),
SpeechConfigCode nvarchar(36) NOT NULL,
OutputSentence nvarchar(500),
PRIMARY KEY(ID),
FOREIGN KEY(SpeechConfigCode) REFERENCES SpeechConfig ON UPDATE CASCADE ON DELETE CASCADE);
I want to allow the user to set it's own custom number, but if he hasn't supplied any such number, the default would be the MAX(IndexPosition) + 1.
I thought about DEFAULT IDENTITY(1,1) but it's impossible.
I also thought about: DEFAULT SELECT MAX(IndexPosition) + 1 FROM SpeechOutputList but it's impossible too (Error: 'Subqueries are not allowed in this context. Only scalar expressions are allowed.').
Anyone has an idea?
You can do it using a SEQUENCE object.
SEQUENCE objects are more flexible than the IDENTITY property. They are not bound to one table and you can use the same SEQUENCE object in multiple places if need be. They also give better performance.
Create a SEQUENCE object, specifying the data type (int), the starting value, and how much to increment by.
CREATE SEQUENCE dbo.IndexPositionSequence
AS int
START WITH 1
INCREMENT BY 1;
Then create the table, and use the NEXT VALUE FOR function to get a value from the SEQUENCE object.
CREATE TABLE dbo.SpeechOutputList
(
ID int NOT NULL IDENTITY(1,1),
IndexPosition int DEFAULT (NEXT VALUE FOR IndexPositionSequence),
SpeechConfigCode nvarchar(36) NOT NULL,
OutputSentence nvarchar(500),
PRIMARY KEY(ID)
)
Then we can insert some values into the table. Some of the values have IndexPosition specified and others not.
INSERT INTO dbo.SpeechOutputList (IndexPosition, SpeechConfigCode, OutputSentence)
VALUES
(123, N'abcd', N'The quick brown fox'),
(DEFAULT, N'efgh', N'jumped over the'),
(124, N'ijkl', N'lazy dog'),
(DEFAULT, N'mnop', N'and some cats');
Then display what's in the table.
SELECT *
FROM dbo.SpeechOutputList;
See MSDN > CREATE SEQUENCE (Transact-SQL): https://msdn.microsoft.com/en-us/library/ff878091.aspx
This is my suggestion
CREATE TABLE dbo.DataTable
(
ID int NOT NULL IDENTITY(1,1),
IndexPosition int,
Name varchar(10)
)
go
create trigger dbo.AI_DataTable on dbo.DataTable
after insert
as
begin
declare #id int = (select ID from inserted)
declare #ip int = (select IndexPosition from inserted)
print #id
print #ip
if (#ip is null)
begin
update dbo.DataTable
set IndexPosition = #id + 1
where ID = #id
end
end
-- you can implement any logic in trigger
-- Note: support bulk insert in trigger
insert into dbo.DataTable(Name) values ('First')
insert into dbo.DataTable (Name) values ('Second')
select * from dbo.DataTable
Result:
+----+---------------+--------+
| ID | IndexPosition | Name |
+----+---------------+--------+
| 1 | 2 | First |
| 2 | 3 | Second |
+----+---------------+--------+
I am not at the computer I did this on but I think I have it figured out
I tested this
You can have a Function as a default vaulue
Just have a function that returns the value
Make the function the default value
select isnull(max(IndexPosition),0) + 1 from table;

default column value

i'm trying to have a table with a column that has a default value.
right now i can only get this by having a trigger change the value to the default, is it possible to have it declared on the table right from the start?
Would it be possible to have something like the Identity, where i don't have to pass the value into the insert?
egx: insert into Direct values(2)
and the table would become
id | item
1 | 2
the id = 1, would be the deafult value
thanks in advance!
you can create constraints at time of table creation or later.
create table
#test
(
id int identity(1,2),
name char(255) default newid(),
code int default 2
)
---if a table contains all default values,you can insert like below
insert into #test
default values
updated as per comments:
create table
#test1
(
id int identity(1,2),
name char(255) default newid(),
code int default 2,
notdf int
)
---if a table contains one default value and rest all are default
insert into #test1(notdf)
select 2
Further if you want to add a default value after table creation you can do it like below
create table
tt1
(
valuue int,
address char(2) not null
)
insert into tt1
select 1,'a'
ALTER TABLE tt1 ADD CONSTRAINT test1 DEFAULT null FOR address;
Use default. You can change an existing column by doing:
ALTER TABLE t ADD CONSTRAINT df_t_column DEFAULT 1 for id;
An identity is trickier. I would suggest copying the data over to a temporary table, dropping the table, creating it with an identity column and reloading the data.

How to re-number T-SQL's system auto-increment Identity column?

I have an auto-increment primary key in a SQL table lets say table look like this:
CREATE TABLE [Table] (--Identifier contains a space and uses a reserved keyword.
[ID] [int] IDENTITY(1,1) NOT NULL ,
[Name] [varchar](50) NULL,
CONSTRAINT [PK__Table] PRIMARY KEY CLUSTERED ([ID] ASC)
);
ID | Name|
1 John
2 Jack
3 Bill
4 Joe
Then I delete row 2 Jack:
ID | Name|
1 John
3 Bill
4 Joe
And what I want to achieve is to change id column so the table will look like this
ID | Name|
1 John
2 Bill
3 Joe
Is there a way to do it?
I will never do that but you can:
create a new autoincrement primary key named ID2
delete ID column
rename ID2 column as ID
Quick and dirty way to do it is, (my way) -->
select * into yournewtable from youroldtable order by yourIdentityColumn;
Then, open up yournewtable's design, make sure yourIdentityColumn is Identity(1,1).
Then, drop youroldtable.
Then, rename yournewtable to youroldtable! ta-da!
Set identity_insert Table off;
Update Table set ID = 3 where ID = 4;
...
Set identity_insert Table on;
Where Table name is Table