0

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

2
  • 1
    Do you mean economical as in server performance or as in shorter, neater code? Commented Oct 24, 2012 at 12:41
  • A bit of both I guess, maybe just what you would consider to be the "best" way. This SPROC is likely to be hit several thousand times per day... Commented Oct 24, 2012 at 12:43

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

From a server performance point of view - Do you think creating a temporary table would be more efficient than either creating lots of variables or just making 2 select statements ?
Not sure how it would effect local performance, but it would only need to open a single transaction which would be a bonus, I guess it would decrease reads but increase cpu load slightly. Not got a machine available I can test it with sadly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.