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
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.
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.
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
-- 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With