Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Output Multiple Local Variables into one Column

Is it possible, using SQL, to output multiple separately defined local variables into one column as separate rows? Eg.

DECLARE var1 INT = 4
DECLARE var2 INT = 5
DECLARE var3 INT = 6

And then select the variables in some manner like

SELECT (var1, var2, var3) AS UserIDs,
       ('u1', 'u2', 'u3') AS Names

Which would produce the following table:

UserIDs | Names
   4    |  u1
   5    |  u2
   6    |  u3
like image 536
MysticVagabond Avatar asked Dec 19 '16 16:12

MysticVagabond


People also ask

How do I pass multiple values to declare a variable in SQL?

Pack the values into one string with comma separated. Set the string as parameter and pass it into the SQL statement. Unpack the values and insert the values into a table, Where customerid in (select id from #temp)

How do I assign a SQL query result to a variable?

To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

Can you declare variables in a SQL view?

You can't declare variables in a view.

How many records can one SQL return in one transaction?

This cumulative limit is 11 times the per-namespace limit. For example, if the per-namespace limit for SOQL queries is 100, a single transaction can perform up to 1,100 SOQL queries. In this case, the cumulative limit is 11 times the per-namespace limit of 100.


1 Answers

Use Table valued constructor

SELECT *
FROM   (VALUES (@var1,'u1'),
               (@var2,'u2'),
               (@var3,'u3')) tc (UserIDs, Names) 
like image 79
Pரதீப் Avatar answered Sep 21 '22 23:09

Pரதீப்