Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008: Fill multiple T-SQL variables from one SELECT query?

To fill one variable with a value from a query I can write following:

SET @TargetID = (SELECT TOP 1 ID FROM @bigDataSet ORDER BY date DESC)

To fill multiple variables from this query, eg. something like:

SET (@TargetID, @TargetName) = ....(SELECT TOP 1 ID, [Name] FROM @bigDataSet ORDER BY date DESC)

what can I write?

like image 464
littlegreen Avatar asked Sep 29 '10 14:09

littlegreen


People also ask

How can I store multiple values in a SQL Server variable?

For example if a new Group_Name was required, then all you need to do is insert it into the Group lookup table rather than modifying the sql code to add the extra group into the list. i am checking that grp name multiple times with different if elseif statements. thats why i created that permanent lookup table.

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 set multiple values in SQL?

To update multiple columns use the SET clause to specify additional columns. Just like with the single columns you specify a column and its new value, then another set of column and values. In this case each column is separated with a column.


1 Answers

SELECT TOP (1) @TargetID=ID, @TargetName=Name 
FROM @bigDataSet 
ORDER BY date DESC
like image 176
Martin Smith Avatar answered Sep 28 '22 19:09

Martin Smith