Insert into column without having IDENTITY - sql

I have a table
CREATE TABLE [misc]
(
[misc_id] [int] NOT NULL,
[misc_group] [nvarchar](255) NOT NULL,
[misc_desc] [nvarchar](255) NOT NULL
)
where misc_id [int] not null should have been IDENTITY (1,1) but is not and now I'm having issues
With a simple form that insert into this table but since misc_id is looking for a number that a user would not know unless they have access to the database.
I know a option would be to create another column make it IDENTITY(1,1) and copy that data.
Is there another way I will be able to get around this?
INSERT INTO misc (misc_group, misc_desc)
VALUES ('#misc_group#', '#misc_desc#')
I have SQL Server 2012

You should re-create your table with the desired identity column. The following statements will get you close. SQL Server will automatically adjust the table's identity field to MAX(misc_id) + 1 as you're migrating data.
You'll obviously need to stop trying to insert misc_id with new records. You'll want to retrieve the SCOPE_IDENTITY() column after inserting records.
-- Note: I'd recommend having SSMS generate your base create statement so you know you didn't miss anything. You'll have to export the indexes and foreign keys as well. Add them after populating data to improve performance and reduce fragmentation.
CREATE TABLE [misc_new]
(
[misc_id] [int] NOT NULL IDENTITY(1,1),
[misc_group] [nvarchar](255) NOT NULL,
[misc_desc] [nvarchar](255) NOT NULL
-- Todo: Don't forget primary key but can be added later (not recommended).
)
GO
SET IDENTITY_INSERT misc_new ON;
INSERT INTO misc_new
(
[misc_id],
[misc_group],
[misc_desc]
)
SELECT
[misc_id],
[misc_group],
[misc_desc]
FROM misc
ORDER BY misc_id;
SET IDENTITY_INSERT misc_new OFF;
GO
EXEC sp_rename 'misc', 'misc_old';
EXEC sp_rename 'misc_new', 'misc';
GO

If altering the table is not an option, you can try having a different table with the latest [misc_id] value inserted, so whenever you insert a new record into the table, you retrieve this value, add 1, and use it as your new Id. Just don't forget to update the table after.

Changing a int column to an identity can cause problems because by default you cannot insert a value into an identity column without use the set identity_insert command on. So if you have existing code that inserts a value into the identity column it will fail. However its much easier to allow SQL Server to insert values(that is change it to an identity column) so I would change misc_id into an identity column and make sure that there are no programs inserting values into misc_id.

In MSSQL 2012 you can use SEQUENCE objects:
CREATE SEQUENCE [dbo].[TestSequence]
AS [BIGINT]
START WITH 1
INCREMENT BY 1
GO
Change 1 in START WITH 1 with MAX value for [misc_id] + 1.
Usage:
INSERT INTO misc (misc_id, misc_group, misc_desc)
VALUES (NEXT VALUE FOR TestSequence, '#misc_group#','#misc_desc#')

Related

what is the default setting for identity_insert in sql database?

I've had to import some data into a db using IDENTITY_INSERT ON, do I set it back to OFF after the import? what is it's default setting? Obviously I need the application to add records/rows to the tables making a new ID each time.
Default setting depends on how you defined the identity column when you created the table
for example
CREATE TABLE Table_Name(ID INT IDENTITY(1,1))
GO
this ID column will have a Seed value of 1 and increment by 1.
By default you cannot add values to Identity column but you can change this default behaviour by executing the following statement.
SET IDENTITY_INSERT Table_Name ON;
Once you have inserted the values then you can set it back to its default behaviour by executing the following statement.
SET IDENTITY_INSERT Table_Name OFF;
even though we can pass values to Identity column but its not a good practice, since it is an auto generated number, if you add the values into identity column yourself and then Identity column generates the same number later on you can have duplicates in your identity column.
so its best to leave identity column alone, and let it generate the values for you.
if it is necessary to add values to Identity column then I would recommend executing the following statement after every you have Indet_Insert ON and add some values to Identity column,
DBCC CHECKIDENT ( table_name, RESEED, 0)
DBCC CHECKIDENT ( table_name, RESEED)
The 1st statement will RESEED the value of Identity column to the smallest values in your identity column,
2nd RESEED statement with out any Seed value provided, will reseed the Identity value to the next available value to the highest value in your identity column.
In case of someone searching for a way to create a key without identity column:
CREATE TABLE [dbo].[TableName](
[Id] [int] NOT NULL PRIMARY KEY
)
instead of
CREATE TABLE [dbo].[TableName](
[Id] [int] IDENTITY(1,1) NOT NULL
)

SQL Server Trigger INSTEAD OF INSERT to Set Timestamps Before Commit

In SQL Server 2008 R2, I am looking to create a trigger that imitates the behavior of an Oracle BEFORE INSERT trigger, where any insert that comes in has the trigger update the UPDATE_TS and CREATE_TS to the current timestamp right before the persist.
To issue I am seeing right now is the error:
An explicit value for the identity column in table 'MY_TABLE' can only be specified when a column list is used and IDENTITY_INSERT is ON
I am not sure if it is a good idea to turn SET IDENTITY INSERT table ON and then
SET IDENTITY INSERT table OFF within the trigger. Maybe that is a possible solution.
Please advise on best practice.
Example Table is called MY_TABLE:
CREATE TABLE [myschema].[MY_TABLE](
[MY_TABLE_ID] [bigint] IDENTITY(1,1) NOT NULL,
[FIELD_TO_UPDATE] [varchar](255) NOT NULL,
[CREATE_TS] [datetime] NULL,
[UPDATE_TS] [datetime] NULL),
PRIMARY KEY (MY_TABLE_ID))
Trigger:
CREATE TRIGGER my_table_create_ts_trigger
ON [mydb].myschema.MY_TABLE
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO MY_TABLE([MY_TABLE_ID], [FIELD_TO_UPDATE], [CREATE_TS], [UPDATE_TS])
SELECT i.MY_TABLE_ID, i.FIELD_TO_UPDATE, GETDATE(), GETDATE()
FROM INSERTED as i
END
Not sure why you are using dynamic SQL, it's not really needed. Also, no need to do an UPDATE afterwards, you can just do:
CREATE TRIGGER my_table_create_ts_trigger
ON [mydb].myschema.MY_TABLE
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO MY_TABLE(<list of every non identity column here>)
SELECT <list of every non identity column and the date here>, GETDATE()
FROM INSERTED
END
Also, you should list the columns explicitely in the INSERT and the SELECT.
I must be a glutton for punishment, but I have a better suggestion. Drop the trigger.
Change your table to:
CREATE TABLE [myschema].[MY_TABLE](
[MY_TABLE_ID] [bigint] IDENTITY(1,1) NOT NULL,
[FIELD_TO_UPDATE] [varchar](255) NOT NULL,
-- change this column to have a default:
[CREATE_TS] [datetime] NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- and this column too, I guess:
[UPDATE_TS] [datetime] NOT NULL DEFAULT CURRENT_TIMESTAMP),
PRIMARY KEY (MY_TABLE_ID))
Why would you allow those columns to be NULL? Why do you want to use an elaborate trigger to replace something that is much simpler to implement with a default constraint?
You don't need the trigger, and I don't understand what benefit it brings or why you want to replicate a BEFORE trigger. An INSTEAD OF trigger is similar, but not exactly the same thing.

Alter an existing Identity Column's Increment value

I am stumped,
I am trying to alter the increment value of Identity columns in a collection of existing MS SQL tables (which all have data) and have been trying to research if it is possible to do without writing custom scripts per table.
I can't find a solution that doesn't require dropping and recreating the tables which would require a different script for each table as they each have different column lists.
for example i want to change the existing table
CREATE TABLE [dbo].[ActionType](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Action] [varchar](100) NOT NULL,
CONSTRAINT [PK_ActionType] PRIMARY KEY CLUSTERED
(
[ID] ASC
) ON [PRIMARY]
) ON [PRIMARY]
To
CREATE TABLE [dbo].[ActionType](
[ID] [int] IDENTITY(1,5) NOT NULL,
[Action] [varchar](100) NOT NULL,
CONSTRAINT [PK_ActionType] PRIMARY KEY CLUSTERED
(
[ID] ASC
) ON [PRIMARY]
) ON [PRIMARY]
Via something like
exec sp_AlterIncrement #TABLE_NAME = 'ActionType', #NEW_ICREMENT = 5
While keeping the data.
This would fix a big deployment issue i am facing right now so any help would be appreciated
You can not alter identity increment after you create it.It is possible just to change seed value with DBCC Chekident .
You should drop and recreate the column.
I had to do that before on a small table and it's fairly easy to do, trick is that you have to update it to something that currently doesn't exist as a key, and then back, since you can't increment it by 1 because that key already exists. It takes 2 updates, for a table with IDs smaller than 100 for example:
update my_table set id = id+100;
update my_table set id = id-99;
But anyways , I do not understand why you want to alter the identity value, Because anyhow you will keep the same as primary key or part of the clustered key.
Also, if any change in the column type is being required then i don't think that there is a possibility without altering the table structure.
Alter table ActionType
Alter column ID
You can also revert to the original structure when not required. This can be used for the specified case as well, As if you require this on demand basis.
Please suggest so that i can provide the further feedback.
Couple of things, maybe too much info but helpful when do stuff like this. The following will set the increment to whatever you want:
DBCC CHECKIDENT ([DB.Schema.Table], reseed, 0) --First record will have a 1. You can set it to any value
If you want to insert data into a table that has an identity but you need to force the value to something specific, do this:
SET IDENTITY_INSERT [DB].[schema].[Table] ON
...Add your data here
SET IDENTITY_INSERT [DB].[schema].[Table] OFF
Sometimes this is necessary.this might provide an answer. For example existing table is identity(1,1) [ex below would be A]
It contains value but you would like to change it to increment of to let's say so that it works well with another table [ex below would be B]
So a would have odd ids + whatever it use to contains.while be would now have even number
this script show you how to do it.
create table A(id int identity(1,1),v char)
insert into A
Select 'A'
union select 'B'
union select 'C'
go
create table B(id int identity(1,2),v char)
go
SET IDENTITY_INSERT B ON
GO
insert into B(Id,v)
Select Id,v from A
go
SET IDENTITY_INSERT B OFF
GO
insert into B
Select 'D'
union select 'E'
go
drop table A
go
EXEC sp_RENAME 'B' , 'A'
go
Select * from A
go
Select max(Id)+1 from A
go
create table B(id int identity(8,2),v char)
go
insert into B
Select 'A'
union select 'B'
union select 'C'
go
Select * from B
If you need to reenumerate or compress your Identity field, the easiest way is as follows:
Convert, temporarily, your identity filed into an integer
Replace the values using for example an Excel sheet in other to fill them up
Copy and Paste the column in your Excel file into the Int field.
Save the table
Open it again in design mode and change back the Int field into an Identity
If this Identity field is used in a child table, make sure you have a trigger to also export the new values into the dependant tables .
And that's all.
If you need to control Identity data in your applicaton, just change it to Int and manage the incremental values with code with the Dmax function.
Hope it helps

Trigger for insert on identity column

I have a table A with an Identity Column which is the primary key.
The primary key is at the same time a foreign key that points towards another table B.
I am trying to build an insert trigger that inserts into Table B the identity column that is about to be created in table A and another custom value for example '1'.
I tried using ##Identity but I keep getting a foreign key conflict. Thanks for your help.
create TRIGGER dbo.tr ON dbo.TableA FOR INSERT
AS
SET NOCOUNT ON
begin
insert into TableB
select ##identity, 1;
end
alexolb answered the question himself in the comments above. Another alternative is to use the IDENT_CURRENT function instead of selecting from the table. The drawback of this approach is that it always starts your number one higher than the seed, but that is easily remedied by setting the seed one unit lower. I think it feels better to use a function than a subquery.
For example:
CREATE TABLE [tbl_TiggeredTable](
[id] [int] identity(0,1) NOT NULL,
[other] [varchar](max)
)
CREATE TRIGGER [trgMyTrigger]
ON [tbl_TriggeredTable]
INSTEAD OF INSERT,UPDATE,DELETE
SET identity_insert tbl_TriggeredTable ON
INSERT INTO tbl_TriggeredTable (
[id],
[other]
)
SELECT
-- The identity column will have a zero in the insert table when
-- it has not been populated yet, so we need to figure it out manually
case i.[id]
when 0 then IDENT_CURRENT('tbl_TriggeredTable') + IDENT_INCR('tbl_TriggeredTable')
ELSE i.[id]
END,
i.[other],
FROM inserted i
SET identity_insert tbl_TriggeredTable OFF
END

Short Sql insert Statement?

In MySql I could have a table with an auto increment column and insert that way:
INSERT INTO tbl VALUES(null, "bla", "bla");
Is there any way to do this with Microsoft SQL Server Express?
Instead of this:
INSERT INTO tbl(`v1`, `v2`) VALUES ("bla", "bla");
Thanks
In Sql Server, you do not need to specify a value for identity columns (I'm guessing this is what the null in mysql is doing).
So, the short syntax for inserting into your table would be:
Insert Into tbl Values('bla', 'bla')
This works regardless of whether the column is declared to be the primary key of the table and also works for any position of the column in the table. That is, even if the column is in the middle as shown below:
Create Table tbl (
[Col1] [varchar](50) NULL,
[Id] [int] IDENTITY(1,1) NOT NULL,
[Col2] [varchar](50) NULL
)
Sql Server will still quite happily interpret the insert statement and take care of the identity insert.
As other posters have mentioned, in Sql Server you actually need to issue the Set Identity_Insert tbl On command to be able to specify a value for identity columns.
I think you are asking whether you can include a reference to the identity column in your insert statement and pass a null or some other magic value in the Values or Select clause. No, you cannot. You cannot pass a value for the identity column unless you use SET IDENTITY_INSERT [table] ON and pass an actual value.
INSERT INTO tbl VALUES(null, 'bla', 'bla');
Works; use single quotes.
From http://msdn.microsoft.com/en-us/library/ms174335.aspx
"If the values in the Value list are
not in the same order as the columns
in the table or do not have a value
for each column in the table,
column_list must be used to explicitly
specify the column that stores each
incoming value."