I'm converting SQL from Teradata to SQL Server
in Teradata, they have the format
SELECT col1, col2 FROM table1 INTO @variable1, @variable2
In SQL Server, I found
SET @variable1 = ( SELECT col1 FROM table1 );
That only allows a single column/variable per statement. How to assign 2 or more variables using a single SELECT statement?
To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.
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.
SELECT @variable1 = col1, @variable2 = col2 FROM table1
SELECT @var = col1, @var2 = col2 FROM Table
Here is some interesting information about SET / SELECT
- SET is the ANSI standard for variable assignment, SELECT is not.
- SET can only assign one variable at a time, SELECT can make multiple assignments at once.
- If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
- When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from it's previous value)
- As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With