Groups | Blog | Home
all groups > sql server (alternate) > january 2004 >

sql server (alternate) : How can you tell what the primary key of a new row will be?


prempel NO[at]SPAM paradata.com
1/7/2004 5:26:13 PM
I need to insert a row into a table in SQL Server 2000. The primary
key for the row is an identity type, so it auto-numbers for me without
needing to put in the value in the insert statement.

My problem, is that after i insert a row, i need to insert another row
in a different table that references the first row. To do that i need
to know the primary key for the original row.

How can i tell what the primary key was? In Oracle, you would check
the sequence before the original insert. Is there a similar feature
in SQL Server? And how would you use it?

(I'm using C# ADO)

Daniel Morgan
1/7/2004 5:58:52 PM
[quoted text, click to view]

I'll leave it to someone that knows more about SQL Server than I to
answer your question. But what you suggest for Oracle doesn't work in
Oracle. Well unless you are in a single-user environment. The solution
in Oracle would be to use the RETURNING clause of the INSERT statement
as in:

DECLARE
x emp.empno%TYPE;
BEGIN
INSERT INTO emp
(empno, ename)
VALUES
(seq_emp.NEXTVAL, 'Morgan')
RETURNING empno
INTO x;

dbms_output.put_line(x);
END;
/

--
Daniel Morgan
http://www.outreach.washington.edu/ext/certificates/oad/oad_crs.asp
http://www.outreach.washington.edu/ext/certificates/aoa/aoa_crs.asp
damorgan@x.washington.edu
(replace 'x' with a 'u' to reply)
Steve Jorgensen
1/8/2004 1:40:26 AM
[quoted text, click to view]

In SQL Server, you check the identity value immediately following the INSERT.
The old way to do this was to check the @@IDENTITY variable, but that's
unrelibale if a trigger also inserts a row into another table, so the new,
AddThis Social Bookmark Button