Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005 Setting a variable to the result of a select query

How do I set a variable to the result of select query without using a stored procedure?


I want to do something like: OOdate DATETIME

SET OOdate = Select OO.Date  FROM OLAP.OutageHours as OO WHERE OO.OutageID = 1 

Then I want to use OOdate in this query:

SELECT COUNT(FF.HALID) from Outages.FaultsInOutages as OFIO INNER join Faults.Faults as FF ON FF.HALID = OFIO.HALID WHERE CONVERT(VARCHAR(10),OO.Date,126) = CONVERT(VARCHAR(10),FF.FaultDate,126))  AND OFIO.OutageID = 1 
like image 287
test Avatar asked Oct 04 '08 10:10

test


People also ask

How do you assign results of SELECT query 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.

Can you DECLARE a variable in a SELECT statement?

In addition to its main usage to form the logic that is used to retrieve data from a database table or multiple tables in SQL Server, the SELECT statement can be used also to assign a value to a previously created local variable directly or from a variable, view or table.


2 Answers

You can use something like

SET @cnt = (SELECT COUNT(*) FROM User) 

or

SELECT @cnt = (COUNT(*) FROM User) 

For this to work the SELECT must return a single column and a single result and the SELECT statement must be in parenthesis.

Edit: Have you tried something like this?

DECLARE @OOdate DATETIME  SET @OOdate = Select OO.Date from OLAP.OutageHours as OO where OO.OutageID = 1  Select COUNT(FF.HALID)  from Outages.FaultsInOutages as OFIO  inner join Faults.Faults as FF      ON FF.HALID = OFIO.HALID  WHERE @OODate = FF.FaultDate     AND OFIO.OutageID = 1 
like image 131
rslite Avatar answered Oct 08 '22 18:10

rslite


-- Sql Server 2005 Management studio

  use Master go DECLARE @MyVar bigint SET @myvar = (SELECT count(*) FROM spt_values); SELECT @myvar  Result: 2346 (in my db) 

-- Note: @myvar = @Myvar

like image 33
Allisson Pereira Avatar answered Oct 08 '22 18:10

Allisson Pereira