Reputation: 59
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.
Upvotes: 1
Views: 407
Reputation: 7338
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)
Upvotes: 3