2012-04-25 57 views
0

我已經創建表入門插入的行ID

create table AA(
    id int , 
    name varchar(20), 
    sname varchar(20) 
) 

現在我插入一個新的價值和獲取插入的行ID:

declare @InsID table (InId int) 
insert into AA (name, sname)select 1, 'John', 'Rock' 
output inserted.id into @output 
Select * from @InsID 

但它爲我的錯誤:消息102,15級,狀態1,行3 「插入」附近的語法不正確。有誰知道似乎是什麼問題?

回答

3
declare @InsID table (InId int) 

insert into AA (name, sname) 
output inserted.id into @InsID 
select 'John', 'Rock' 

Select * from @InsID 
+0

感謝的例子見here,這正是我需要的 – Brezhnews 2012-04-25 10:34:59

1

假設在你的表中的ID列被定義爲標識列,則:

SELECT SCOPE_IDENTITY() 

請參見本文的詳細信息: http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/

如果你真的想使用OUTPUT條款你的語法是錯誤的。輸出必須在表後,立即來了,前值:

declare @InsID table (InId int) 

insert into AA (name, sname) 
output inserted.id into @InsID 
select 'John', 'Rock' 

Select * from @InsID 

每個