[SQL Server]SQL Server数据库中获取插入数据自增ID的最好的方式是什么?
方案一、使用 OUTPUT (推荐)
USE AdventureWorks2008R2;
GO
DECLARE @MyTableVar table( NewScrapReasonID smallint,
Name varchar(50),
ModifiedDate datetime);
INSERT Production.ScrapReason
OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate
INTO @MyTableVar
VALUES (N'Operator error', GETDATE());
--Display the result set of the table variable.
SELECT NewScrapReasonID, Name, ModifiedDate FROM @MyTableVar;
--Display the result set of the table.
SELECT ScrapReasonID, Name, ModifiedDate
FROM Production.ScrapReason;
GO
方案二、使用 scope_identity() 函数
在插入语句后面添加如下语句:
SELECT CAST(scope_identity() AS int);
在C#代码中使用如下方法获取返回的自增ID值:
var newId = command.ExecuteScalar();
版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。
发表评论
登录用户才能发表评论, 请 登 录 或者 注册