Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

1 SET statement for multiple variables like declare statement

Is there a way to set all variables with one set statment, like you can with a declare statement?

For example:

   Declare @Test VARCHAR(10),                 @Test2 VARCHAR(10),                 @Test3 INT          SET @Test = 'test'         SET @Test2 = 'Test2'         SET @Test3 = 1 

Where I want to do something like the below, but the below does not work:

Set @Test = 'test',     @Test2 = 'Test2',     @Test3 = 3 
like image 500
mameesh Avatar asked Aug 25 '11 16:08

mameesh


People also ask

How do you set multiple variables?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.

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 variables in the Declare statement?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.


1 Answers

Instead of SET, use SELECT.

SELECT @Test = 'test',        @Test2 = 'Test2',        @Test3 = 3; 

Here's a great article on SET vs SELECT in SQL Server / TSQL.

like image 173
p.campbell Avatar answered Sep 29 '22 18:09

p.campbell