8

In SQL server, how can I place the value of more than one column in variables using one query?

Ex: my query is:

SELECT ET.ID,ET.Description,ET.DefaultTemplateText 
FROM TBL_EMAILTEMPLATE ET 
WHERE ET.NAME='OneWeekReminder'

I want to place the column values in variables.

4 Answers 4

16

You can use the following syntax:

Declare @id INT
Declare @desc VarChar(100)
Declare @template VarChar(100)

SELECT @id = ET.ID, @desc = ET.Description, @template = ET.DefaultTemplateText 
FROM TBL_EMAILTEMPLATE ET 
WHERE ET.NAME='OneWeekReminder'
Sign up to request clarification or add additional context in comments.

1 Comment

If the query returns multiple rows, it would just set the values multiple times
6

declare the variables first then set them in the select clause.

declare
    @ID int,
    @Description varchar(10),
    @DefaultTemplateText varchar(10)

select
    @ID = ET.ID,
    @Description = ET.Description,
    @DefaultTemplateText = ET.DefaultTemplateText
from
    TBL_EMAILTEMPLATE ET
where
    ET.NAME = 'OneWeekReminder'

Comments

4

You can separate multiple assignments with a comma. For example:

declare @a varchar(50)
declare @b varchar(50)

select 
    @a = et.Description
,   @b = et.DefaultTemplateText
from YourTable

Comments

3

Assuming only one row,

SELECT @id = ET.ID, @Description = ET.Description, @DefaultTemplateText = ET.DefaultTemplateText
FROM TBL_EMAILTEMPLATE ET 
WHERE ET.NAME='OneWeekReminder'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.