Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set multiple local variables in one line using T-SQL?

declare @inserted bit
declare @removed bit

I know it's possible to set them like below:

SELECT @inserted = 0, @removed = 0

but would it be possible to make this even simpler and use something like:

SET @inserted, @removed = 0

Many thanks

like image 728
The Light Avatar asked Nov 25 '11 12:11

The Light


People also ask

Can we DECLARE multiple variables at once in SQL?

Regarding feature of SQL Server where multiple variable can be declared in one statement, it is absolutely possible to do. From above example it is clear that multiple variables can be declared in one statement.

Can you assign multiple values to a variable in SQL?

Assigning multiple values to multiple variablesIf you have to populate multiple variables, instead of using separate SET statements each time consider using SELECT for populating all variables in a single statement. This can be used for populating variables directly or by selecting values from database.

How do I select multiple values in SQL?

To select multiple values, you can use where clause with OR and IN operator.


1 Answers

How about:

declare @inserted BIT = 0, @removed BIT = 0

Works in SQL Server 2008 and up (you didn't specify which version of SQL Server....)

Update: ok, so you're stuck on SQL Server 2005 - in that case, I believe this is the best you can do:

DECLARE @inserted BIT, @removed BIT
SELECT @inserted = 0, @removed = 0
like image 164
marc_s Avatar answered Sep 23 '22 06:09

marc_s