views:

42

answers:

4

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.

Thanks in advance for the help

+5  A: 

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'
Oded
If the query returns multiple rows, it would just set the values multiple times
Andomar
@Andomar - thanks for the correction. Updated answer.
Oded
+2  A: 

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'
JC
+2  A: 

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
Andomar
+2  A: 

Assuming only one row,

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