use*_*269 32 sql sql-server-2008
在使用存储过程的SQL Server中是否可以在表中返回一些值插入的表中的标识列值?例如,如果我们在表中插入数据,则使用存储过程:
表TBL
因此,如果我运行存储过程插入一些值,如:
Insert into TBL (Name, UserName, Password)
Values ('example', 'example', '$2a$12$00WFrz3dOfLaIgpTYRJ9CeuB6VicjLGhLset8WtFrzvtpRekcP1lq')
Run Code Online (Sandbox Code Playgroud)
如何返回UserID此插入的值.我需要UserID的值用于其他一些操作,任何人都可以解决这个问题吗?
Ami*_*ngh 73
Insert into TBL (Name, UserName, Password) Output Inserted.IdentityColumnName
Values ('example', 'example', 'example')
Run Code Online (Sandbox Code Playgroud)
Md.*_*lam 11
发送输出参数,如
@newId int output
Run Code Online (Sandbox Code Playgroud)
在最后使用
select @newId = Scope_Identity()
return @newID
Run Code Online (Sandbox Code Playgroud)
SELECT SCOPE_IDENTITY()
Run Code Online (Sandbox Code Playgroud)
插入语句之后
请参阅以下链接
http://msdn.microsoft.com/en-us/library/ms190315.aspx
小智 5
您可以使用 SqlServer 的 OUTPUT 子句显式取回身份列: 假设您有一个名为 ID 的身份/自动增量列:
$sql='INSERT INTO [xyz].[myTable] (Field1, Field2, Field3) OUTPUT Inserted.ID VALUES (1, 2, '3')';
Run Code Online (Sandbox Code Playgroud)
请注意,在 Perl DBI 中,您将执行 INSERT 语句,就像它是 SELECT 一样。并捕获输出,就像它是一个 SELECT 一样
$sth->execute($sql);
@row=$sth->fetchrow_array; #Only 1 val in 1 row returned
print "Inserted ID: ", $row[0], "\n";
Run Code Online (Sandbox Code Playgroud)
据推测,这是更可取的,因为它不需要另一个请求。