[英]Setting a variable to the result of a select query SQL server 2012
I am trying to find the most economical way of achieving a way to return the data I want and also updating another table within the same Stored Procedure. 我试图找到最经济的方法来实现返回所需数据的方式,并在同一存储过程中更新另一个表。
I have drastically simplified my SQL below to illustrate my issue. 我在下面大大简化了我的SQL以说明我的问题。 Here's what I want to achieve : 这是我要实现的目标:
DECLARE @UserID INT
SELECT TOP(1) @UserID = UserID, UserName, email, (#Loads of other columns#) FROM Users
UPDATE Logins SET LoggedIn = 1 WHERE UserID = @UserID
I understand I could do this by making sure that all returned columns are assigned to a local variable, but there are too many to be an efficient SPROC. 我知道我可以通过确保将所有返回的列都分配给局部变量来做到这一点,但是有太多的东西不能成为有效的SPROC。
I don't want to have to do the SELECT statement twice (once to return the data and once to set the variable, ready for the update statement) 我不想重复执行SELECT语句(一次返回数据,一次设置变量,为更新语句做准备)
Any suggestions guys ? 有什么建议吗? Thanks, Scott 谢谢,斯科特
You could use OUTPUT
to get values to a local table variable but you still have to use a local SELECT
to get a single value from the table variable. 您可以使用OUTPUT
将值获取到本地表变量,但仍然必须使用本地SELECT
从表变量中获取单个值。
DECLARE @TBL TABLE(userid int, username varchar(50), email varchar(50), logged bit)
DECLARE @userid int
UPDATE TOP (1) Users
SET logged = 1
OUTPUT deleted.* INTO @TBL
SELECT top (1) @userid = userid from @TBL
SELECT @userid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.