4

I have to set several variables in a stored procedure in SQL Server. Currently, I use individual SELECT statements to set each variable. I don't know if there is a better/ more efficient way of doing it. This is a sample of 2 variables but there are 8 variables total.

DECLARE @source nvarchar(250)
DECLARE @target nvarchar(250) 

SET @source = (SELECT Value FROM ApplicationSetting WHERE Key = 'Source')
SET @target = (SELECT Value FROM ApplicationSetting WHERE Key = 'Target')

Currently, I use 8 individual select statements to set each variable. Is this the most efficient way to set this many variables?

1 Answer 1

4

In a single select we can assign both the variables using conditional aggregate

Try this way

DECLARE @source NVARCHAR(250)
DECLARE @target NVARCHAR(250)

SELECT @source = Max(CASE WHEN KEY = 'Source' THEN Value END),
       @target = Max(CASE WHEN KEY = 'Target' THEN Value END)
FROM   ApplicationSetting
WHERE  KEY IN( 'Source', 'Target' ) 
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! I could not figure out how to use CASE...adding MAX was the ticket. Thanks!

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.