Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set multiple T-SQL variables in a single SELECT query?

I have 3 variables: @testid, @sampleid and @clientid.

How can I set @sampleid and @clientid by executing this query once?

SELECT
  [sample].sampleid,
  [client].clientid
FROM
  dbo.[test]
  LEFT OUTER JOIN dbo.[sampleslice] ON dbo.[test].samplesliceid = dbo.[sampleslice].samplesliceid
  LEFT OUTER JOIN dbo.[sample] ON dbo.[sampleslice].sampleid = dbo.[sample].sampleid
  LEFT OUTER JOIN dbo.[client] ON dbo.[sample].clientid = dbo.[client].clientid
WHERE
  testid = @testid
like image 309
MacGyver Avatar asked Aug 02 '11 19:08

MacGyver


People also ask

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

DECLARE @sampleid YOUR_VAR_TYPE;
DECLARE @clientid YOUR_VAR_TYPE;

SELECT
   @sampleid = [sample].sampleid, 
   @clientid = [client].clientid
FROM dbo.[test]


-- The variables are now initialized. You can now use them below.above
like image 156
gbn Avatar answered Sep 22 '22 04:09

gbn