1

Can I assign multiple variables under a single condition in a select statement in SQL Server (I am too stupid for dynamic sql):

For example in Visual Basic or many other languages you might have

If x=1 then z=4 y=2 End if

I don't think CASE works, because I think you can only assign to one variable.

0

2 Answers 2

3

The trick is that if you can get away with the assignments on one line, then you dont need BEGIN/END block as the other person has suggested. Although things will start to look ugly. Here's some examples that achieve what you want:

-- using set syntax on one line
declare @x int, @y int , @z int
set @x=1
IF @x=1 set @y=2 set @z=4
print 'y:' + cast(@y as varchar) + ' z:' + cast(@z as varchar)
GO

-- using select syntax, a little prettier on one line
declare @x int, @y int , @z int
set @x=1
IF @x=1 SELECT @y=2,@z=4
print  'y:' + cast(@y as varchar) + ' z:' + cast(@z as varchar)
GO
-- using being/end
declare @x int, @y int , @z int
set @x=1
IF @x=1 
BEGIN
    set @y=2
    set @z=4
END
print 'y:' + cast(@y as varchar) + ' z:' + cast(@z as varchar)
Sign up to request clarification or add additional context in comments.

1 Comment

1

Wrap the assignments in BEGIN... END

Comments

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.