Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing column values in variables using single SQL query

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.

like image 735
Shyju Avatar asked Mar 30 '10 17:03

Shyju


People also ask

How do I assign a column value to a variable in SQL?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

How do I pass multiple values to a single variable in SQL?

Pack the values into one string with comma separated. Set the string as parameter and pass it into the SQL statement. Unpack the values and insert the values into a table, Where customerid in (select id from #temp)

How do you declare and assign value to a variable in SQL?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.


2 Answers

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'
like image 97
Oded Avatar answered Oct 08 '22 20:10

Oded


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'
like image 45
JC Ford Avatar answered Oct 08 '22 21:10

JC Ford