On SQL INSERT can I use the identity column for part of the insert data in another column at the same time? - sql

CREATE TABLE Table1 :
Id int IDENTITY(1,1),
PK_Column1 nvarchar(50) Primary Key.
INSERT INTO Table1 (PK_Column1) VALUES ('Name'+Id)
Result:
Id PK_Column1
1 Name1
Is this possible? Or do I need to manage the Id column myself for this to work?

From the documentation:
After an INSERT, SELECT INTO, or bulk copy statement completes, ##IDENTITY contains the last identity value generated by the statement.
This applies to all the other identity checkers.
You should probably write a little SP to update the record immediately after your insert if this is what you need. Given that your primary_key appears to be some unusual composite of the ID and a varchar, you would also be best reviewing your data model.
It's important to note the difference with ##IDENTITY and SCOPE_IDENTITY():
##IDENTITY and SCOPE_IDENTITY return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; ##IDENTITY is not limited to a specific scope.

Related

Inserting new rows and generate a new id based on the current last row

The primary key of my table is an Identity column of an ID. I want to be able to insert a new row and have it know what the last ID in the table currently is and add one to it. I know I can use Scope Identity to get the last inserted column from my code, but I am worried about people manually adding entries in the database, because they do this quite often. Is there a way I can look at the last ID in the table and not just the last ID my code inserted?
With a SQL Identity column, you don't need to do anything special. This is the default behavior. SQL Server will handle making sure you don't have collisions regardless of where the inserts come from.
The ##Identity will pull the latest identity, and scope_identity will grab the identity from the current scope.
A scope is a module: a stored procedure, trigger, function, or batch. Therefore, if two statements are in the same stored procedure, function, or batch, they are in the same scope.
If you don't want to allow manual entries to the primary column, then you can add Identity constraint to it along with primary key constraint.
Example, while creating a table,
CREATE Table t_Temp(RowID Int Primary Key Identity(1,1), Name Varchar(50))
INSERT Into t_Temp values ('UserName')
INSERT Into t_Temp values ('UserName1')
SELECT * from t_Temp
You can query the table and get the next available code in one SQL query:
SELECT COALESCE(MAX(CAST("RowID" AS INT)),0) +1 as 'NextRowID' from <tableName>
The "0" here is a default, meaning if there are no rows found, the first code returned would be (0+1) =1
Generally I have 999 instead of the 0 as I like my RowID/primary key etc. to start at 1000.

Sql Server - How to get last id inserted into table

I'm trying to get the last id inserted into a table.
I was using
SELECT IDENT_CURRENT('TABLE')
But the problem is that it doesn't return the last inserted id, it returns the max inserted id.
For example, if i do:
INSERT INTO 'TABLA' (ID) VALUES (100)
SELECT IDENT_CURRENT('TABLE') returns 100
but then if i do
INSERT INTO 'TABLA' (ID) VALUES (50)
SELECT IDENT_CURRENT('TABLE') returns 100
and I want to get 50
I need the ID of a specific table, and I generate the id dinamically, so it's not an identity
How can i do it?
From your code, it looks like ID is not an identity (auto-increment) column, so IDENT_CURRENT isn't going to do what you are expecting.
If you want to find the last row inserted, you will need a datetime column that represents the insert time, and then you can do something like:
SELECT TOP 1 [ID] FROM TABLEA ORDER BY [InsertedDate] DESC
Edited: a few additional notes:
Your InsertedDate column should have a default set to GetDate() unless your application, stored procs or whatever you use to perform inserts will be responsible for setting the value
The reason I said your ID is not an identity/auto-increment is because you are inserting a value into it. This is only possible if you turn identity insert off.
SQL Server does not keep track of the last value inserted into an IDENTITY column, particularly when you use SET IDENTITY_INSERT ON;. But if you are manually specifying the value you are inserting, you don't need SQL Server to tell you what it is. You already know what it is, because you just specified it explicitly in the INSERT statement.
If you can't get your code to keep track of the value it just inserted, and can't change the table to have a DateInserted column with a default of CURRENT_TIMESTAMP (which would allow you to see which row was inserted last), perhaps you could add a trigger to the table that logs all inserts.
SELECT SCOPE_IDENTITY()
will return the last value inserted in current session.
Edit
Then what you are doing is the best way to go just make sure that the ID Column is an IDENTITY Column, IDENT_CURRENT('Table_name'), ##IDENTITY and SCOPE_IDENTITY() returns last value generated by the Identity column.
If the ID column is not an Identity Column, all of these functions will return NULL.

Using IDENT_CURRENT() of table during insert into table

I have an existing table that has an identity column and a column that has a constraint to ensure that it matches the value in the identity column.
(I know that this is not a good design, but it is an old table that can not be changed at the moment)
I know that I can use the IDENT_CURRENT('mytable') as a value during the insert to put the newly created identity value into the other column (FakeID).
INSERT INTO MyTable (FakeID)
SELECT IDENT_CURRENT('MyTable')
I have seen that this has issues when inserting multiple records, but for this use I am only inserting a single record.
My question is how safe is this to use?
Mainly, is there a risk from inserts made under different sessions or in a different scope?
Also, does this behave as expected when the table is truncated?
Any other suggestions are welcome.
SCOPE_IDENTITY() is going to be a safer bet here. If someone inserts into the table before this part of your transaction runs, IDENT_CURRENT will grab the newly generated Id from the other transaction.
So I would declare a variable and set its value to SCOPE_IDENTITY(), something like this
DECLARE #Id INT
SET #Id = SCOPE_IDENTITY()
INSERT INTO MyTable (FakeID)
SELECT #Id
Here are some posts on a similar issue:
http://bytes.com/topic/sql-server/answers/471026-ident_current-problem
IDENT_CURRENT equivalent for current session

Primary key value after insertion of row in SQL Server 2005

In SQL Server 2005 I am inserting a row into a table using a stored procedure and I want to fetch the new primary key value just after inserting that row. I am using following approach to get primary key value after insertion row
Create Proc Sp_Test
#testEmail varchar(20)=null,-- Should be Unique
#testName varchar(20)=null -- Should be Unique
as
begin
insert into tableTest (testUserEmail,testUserName)values (#testValue,#testName)
select MAX(ID) from tableTest --ID is Primary Key
--or
select ID from tableTest where testUserEmail =#testValue and testUserName = #testName
--or
select SCOPE_IDENTITY() as ID
end
Please suggest me which approach is better to perform described task.
By all means - use the SCOPE_IDENTITY() if your ID column is an INT IDENTITY - only that will give you the correct results!
The first approach with the MAX(ID) will fail terribly if you have multiple clients inserting rows almost at the same time - you'll get false results back. Don't use that!
The third approach might fail if another entry with the same values for E-Mail and name already exists.
Also, as a side-note: you should never use sp_ as your prefix! This is a Microsoft-reserved prefix and has downsides in terms of performance - use something else.
If you have an Identity column as primary key you should use SCOPE_IDENTITY()
You could also use the OUTPUT Clause to return the ID.
insert into tableTest(testUserEmail,testUserName)
output inserted.ID
values (#testValue, #testName)

Using ##IDENTITY in SQL on a specific table

How can I get the ##IDENTITY for a specific table?
I have been doing
select * from myTable
as I assume this sets the scope, from the same window SQL query window in SSMS I then run
select ##IDENTITY as identt
It returns identt as null which is not expected since myTable has many entrie in it already..
I expect it to return the next available ID integer.
myTable has a ID column set to Primary key and auto increment.
You can use IDENT_CURRENT
IDENT_CURRENT( 'table_name' )
Note that IDENT_CURRENT returns the last identity value for the table in any session and any scope. This means, that if another identity value was inserted after your identity value then you will not retrieve the identity value that you inserted.
You can only truly use SELECT ##IDENTITY after an insert - the last insert into a table that has an IDENTITY column is the value you'll get back.
You cannot "limit" it to a table - the value in ##IDENTITY - and by the way, I'd strongly recommend using SCOPE_IDENTITY() instead!! - is the last value on any IDENTITY column that was set.
The problem with ##IDENTITY is that it will report back the last IDENTITY value inserted into any table - if your INSERT into your data table will cause e.g. a trigger to write an entry into an Audit table and that Audit table has an IDENTITY field, you'll get back that IDENTITY value - not the one inserted into your table. SCOPE_IDENTITY() solves that.
IDENT_CURRENT does what you want. But don't.
This is in addition to marc_s' answer
I've never known ##IDENTITY to be used this way, i've only ever used it to access the ID of a newly inserted record.
That's correct. ##IDENTITY cannot be used the way you think it can be. It can only be used after an INSERT into a table. Let's consider this for a scenario:
You have two tables: Order (Primary Key: OrderID), OrderDetails (Foreign Key: OrderID)
You perform
INSERT INTO Order
VALUES('Pillows')
-- Note that OrderId is not mentioned in Values since it is auto number (primary key)
Now you want to perform insert into OrderDetail. But you don't always remember how many records there were in Order table prior to you having inserted the record for 'Pillows' and hence you don't remember what was the last PrimaryKey inserted into Order table. You could but even then you wouldn't want to specifically mention to insert (let's say OrderID of 1) when you insert into OrderDetail table.
Hence, your OderDetail insert would work kinda like so:
INSERT INTO OrderDetail
VALUES (##IDENTITY,'Soft Pillows')
Hope this explains the user of ##IDENTITY.