简体   繁体   中英

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. 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.

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)

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.

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

Fiddle Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM