I am trying to add a range or exclude numbers from an auto increment column in sql.
We have an auto increment column regarding Job Numbers since each Job is unique. The problem is we treat ourselves as a client as well, and the job number as 99999 where as the other job numbers end for example 10500. When the auto increment takes place, it follows on from 99999. This there a way to exclude this or do I have to manual set the IDENTITY_INSERT ON and insert the ID myself?
Thanks in advance
You can set off the auto-increment in the "Microsoft SQL Server"
Check: SQL-How to Insert Row Without Auto incrementing a ID Column?
In this way you can set the ID's yourself.
Set Identity_Insert [TableName] On
-- --------------------------------------------
Insert TableName (pkCol, [OtherColumns])
Values(pkValue, [OtherValues])
-- ---- Don't forget to turn it back off ------
Set Identity_Insert [TableName] Off
Related
I am trying to manually add records to a SQL table
However in this table we have a column called Trackseq this column determines how the data is viewed on our CMS system.
The highest TrackSeq will appear first.
I want to manually add a new row but i want the code to check based on CLNTID what the current trackSeq is and add one to it. So if the trackseq of the last record was 10 I want the new record to go in with a trackseq of 11.
Here is my code.
INSERT INTO tbl_CommTracking ( CLNTID,
TRACKSEQ,
COMMDATE,
COMMTIME,
PRODCODE,
COMMTYPE,
EMPLOYEEID,
COMMDETAILS,
COMMSTATUS)
VALUES ('0000005566','999',GETDATE(),GETDATE(),'BS','Note','0000000786','Testing a manual import','A')
Thanks
Assuming TRACKSEQ is a numeric format, you can read the actual highest value and store it in a variable to use in your insert statement.
Please note that, in case of high concurrency, you may want to synchronize this execution in order to avoid duplicate #ts values.
As stated by #Tim Biegeleisen above, an IDENTITY column is best suited for this kind of tasks, but keep in mind that it may leave holes in number sequence in case of DELETE and failed INSERTS.
Eg:
DECLARE #ts int; --or whatever numeric datatype it is
SELECT #ts = MAX(TRACKSEQ) + 1 FROM tbl_CommTracking
INSERT INTO tbl_CommTracking (
--...
TRACKSEQ
--..
)
VALUES (
--...
#ts
--...
)
You should probably make TRACKSEQ an auto increment column. First drop your current TRACKSEQ column, then add it back:
ALTER TABLE tbl_CommTrackingDROP COLUMN TRACKSEQ;
ALTER TABLE tbl_CommTracking ADD TRACKSEQ INT IDENTITY;
Note that typically you would also make TRACKSEQ the primary key of the table. If you don't want to, that's OK, but then you'll have to make sure you can generate your own unique values for the CLNTID column.
It isn't entirely clear why you need this; if you just want the latest records, use the date/timestamp column available, which would have been set during insertion.
I get the following error message:
{returnResult=Cannot insert explicit value for identity column in table 'player' when IDENTITY_INSERT is set to OFF.;Result=Cannot insert explicit value for identity column in table 'player' when IDENTITY_INSERT is set to OFF.;}
I'm currently trying to auto-increment a player_id in a player table every time a new player is created. I set this up in Windows SQL Server Management Studio.
What should my query look like?
INSERT INTO player (player_id, player_type_id)
VALUES('','1')
I have one manual value, but I want the user_id to be unique each time it is created. All help greatly appreciated!
If you have correctly set the player_id field up to auto increment, you simply leave that column out of your INSERT statement, and just supply the other values.
INSERT INTO player (player_type_id)
VALUES('1')
If you believe your column is not currently set to auto increment, have a look at this.
You have to set identity insert on (that is if you want to supply your own identity value instead of asking MYSQL to generate one for you )
SET IDENTITY_INSERT Table1 ON
Then execute your query..by supplying your own value for that column
and then turn it off after that..(Since you want only one manual insert done)
SET IDENTITY_INSERT Table1 OFF
I am using SQL Server Management Studio and I want to change an auto increment primary key value of a table row, with a different value. SQL Server Management Studio after opening the table for edit, shows this field grayed for all rows, of course.
Is it possible? I want to use the number of a row we deleted by mistake, therefore it's valid (there is no conflict with other primary key values) and - most important of all - the next row added in the DB should have an intact auto incremented value.
Thanks.
EDIT: losing the link with other table records on this PK is not an issue for this row. We can restore it manually.
Not necessarily recommended but, insert a copy of the row where you want to change the number, but with the ID you require:
SET IDENTITY_INSERT aTable ON
GO
-- Attempt to insert an explicit ID value of 3
INSERT INTO aTable (id, product) VALUES(3, 'blah')
GO
SET IDENTITY_INSERT aTable OFF
GO
Then delete the row with the number you don't want (after you update any FK references).
More details here: http://technet.microsoft.com/en-us/library/aa259221(v=sql.80).aspx
For posterity, to clarify the question in the comment below, the auto increment value will only be affected if you insert a value greater than the current maximum.
Quoting from linked article:
If the value inserted is larger than the current identity value for
the table, SQL Server automatically uses the new inserted value as the
current identity value.
Is it possible in SQL (SQL Server) to retrieve the next ID (integer) from an identity column in a table before, and without actually, inserting a row? This is not necessarily the highest ID plus 1 if the most recent row was deleted.
I ask this because we occassionally have to update a live DB with new rows. The ID of the row is used in our code (e.g. Switch (ID){ Case ID: } and must be the same. If our development DB and live DB get out of sync, it would be nice to predict a row ID in advance before deployment.
I could of course SET IDENTITY OFF SET INSERT_IDENTITY ON or run a transaction (does this roll back the ID?) etc but wondered if there was a function that returned the next ID (without incrementing it).
try IDENT_CURRENT:
Select IDENT_CURRENT('yourtablename')
This works even if you haven't inserted any rows in the current session:
Returns the last identity value generated for a specified table or view. The last identity value generated can be for any session and any scope.
Edit:
After spending a number of hours comparing entire page dumps, I realised there is an easier way and I should of stayed on the DMVs.
The value survives a backup / restore, which is a clear indication that it is stored - I dumped all the pages in the DB and couldn't find the location / alteration for when
a record was added. Comparing 200k line dumps of pages isn't fun.
I had used the dedicated admin console I took a dump of every single internal table exposed inserted a row and then took a further dump of the system tables. Both of the dumps were identical, which indicates that whilst it survived, and therefore must be stored, it is not exposed even at that level.
So after going around in a circle I realised the DMV did have the answer.
create table foo (MyID int identity not null, MyField char(10))
insert into foo values ('test')
go 10
-- Inserted 10 rows
select Convert(varchar(8),increment_value) as IncrementValue,
Convert(varchar(8),last_value) as LastValue
from sys.identity_columns where name ='myid'
-- insert another row
insert into foo values ('test')
-- check the values again
select Convert(varchar(8),increment_value) as IncrementValue,
Convert(varchar(8),last_value) as LastValue
from sys.identity_columns where name ='myid'
-- delete the rows
delete from foo
-- check the DMV again
select Convert(varchar(8),increment_value) as IncrementValue,
Convert(varchar(8),last_value) as LastValue
from sys.identity_columns where name ='myid'
-- value is currently 11 and increment is 1, so the next insert gets 12
insert into foo values ('test')
select * from foo
Result:
MyID MyField
----------- ----------
12 test
(1 row(s) affected)
Just because the rows got removed, the last value was not reset, so the last value + increment should be the right answer.
Also going to write up the episode on my blog.
Oh, and the short cut to it all:
select ident_current('foo') + ident_incr('foo')
So it actually turns out to be easy - but this all assumes no one else has used your ID whilst you got it back. Fine for investigation, but I wouldn't want to use it in code.
This is a little bit strange but it will work:
If you want to know the next value, start by getting the greatest value plus one:
SELECT max(id) FROM yourtable
To make this work, you'll need to reset the identity on insert:
DECLARE #value INTEGER
SELECT #value = max(id) + 1 FROM yourtable
DBCC CHECKIDENT (yourtable, reseed, #value)
INSERT INTO yourtable ...
Not exactly an elegant solution but I haven't had my coffee yet ;-)
(This also assumes that there is nothing done to the table by your process or any other process between the first and second blocks of code).
You can pretty easily determine that the last value used is:
SELECT
last_value
FROM
sys.identity_columns
WHERE
object_id = OBJECT_ID('yourtablename')
Usually, the next ID will be last_value + 1 - but there's no guarantee for that.
Marc
Rather than using an IDENTITY column, you could use a UNIQUEIDENTIFIER (Guid) column as the unique row identifer and insert known values.
The other option (which I use) is SET IDENTITY_INSERT ON, where the row IDs are managed in a source controlled single 'document'.
I have a table that has a forced auto increment column and this column is a very valuable ID that is retained through out the entire app. Sorry to say it was poor development on my part to have this be the auto incrementing column.
So, here is the problem. I have to insert into this table an ID for the column that has already been created and removed from the table. Kind of like resurrecting this ID and putting it back into the table.
So how can I do this programatically do this without turning the column increment off. Correct me if I am wrong, if I turn it off programatically, It will restart at 0 or 1 and I don't want that to happen...
If you are in Microsoft SQL Server, you can "turn off" the autoIncrementing feature by issuing the statement Set Identity_Insert [TableName] On, as in:
Set Identity_Insert [TableName] On
-- --------------------------------------------
Insert TableName (pkCol, [OtherColumns])
Values(pkValue, [OtherValues])
-- ---- Don't forget to turn it back off ------
Set Identity_Insert [TableName] Off
In addition to Charles' answer (which is now 100% correct :-) and which preserves the current value of the IDENTITY on the table), you might also want to check the current value of an IDENTITY on a table - you can do this with this command here:
DBCC CHECKIDENT('YourTableName')
If you ever need to actually change it, you can do so by using this command here:
DBCC CHECKIDENT ('YourTableName', RESEED, (new value for IDENTITY) )
Actually, the code above for INDENTITY_INSERT is correct - turning it ON tells the server you want to insert the values yourself. It allows you to insert values into an IDENTITY column. You then want to turn it back off (allowing the server to generate and insert the values) when you are done.
bulk insert tablename from 'C:\test.csv' with (rowterminator = '\n',fieldterminator = ',',KEEPIDENTITY)