'store the variable for the call inside the select sql server
how to store the variable for the call inside the select example:
DECLARE @Qty INT, @workdays INT, @dailygoal INT, @bufferstock INT;
SELECT
@Qty = SUM(qty) [qty],
@workdays = 25 [workdays],
@dailygoal = (SUM(qty) / 25) [dailygoal],
@bufferstock = (@dailygoal * MAX(leadtime)) [bufferstock]
FROM table
Solution 1:[1]
Remove Alias Name ..
DECLARE @Qty INT, @workdays INT, @dailygoal INT, @bufferstock INT;
SELECT
@Qty = SUM(Bonus_amount),
@workdays = 25,
@dailygoal = (SUM(Bonus_amount) / 25),
@bufferstock = (@dailygoal * 5)
FROM [dbo].[Bonus]
select @Qty,@workdays,@dailygoal,@bufferstock
Solution 2:[2]
The query you have will error, due to your aliases. When you assign a variable in a SELECT you do not alias the column.
Also, although you can do syntax like you have, where you reference a variable assigned elsewhere in the statement, I would err against it; though not documented I would not be surprised if has the same antipattern as documented in Antipattern use of recursive variable assignment and that the latter variable could be derived prior to the former. This would mean that the variable @bufferstock could be assigned the value NULL, as the value of @dailygoal was NULL when the expressed was determined.
Instead, just repeat the expression:
DECLARE @V1 int,
@V2 int;
SELECT @V1 = SUM(V.I),
@V2 = SUM(V.I) * MAX(V.I)
FROM (VALUES(1),(2),(3))V(I);
SELECT @V1,
@V2;
If you don't want to do that, then use a derived table (a CTE or Subquery) to define the expression instead. I use a CTE here:
DECLARE @V1 int,
@V2 int;
WITH CTE AS(
SELECT SUM(V.I) AS S,
MAX(V.I) AS M
FROM (VALUES(1),(2),(3))V(I))
SELECT @V1 = S,
@V2 = S*M
FROM CTE;
SELECT @V1,
@V2;
Using a derived table for your query would mean something like the following:
DECLARE @Qty int,
@workdays int,
@dailygoal int,
@bufferstock int;
WITH CTE AS(
SELECT SUM(qty) AS qty,
SUM(qty) / 25 AS dailygoal,
MAX(leadtime) AS leadtime
FROM dbo.[table])
SELECT @Qty = qty,
@workdays = 25,
@dailygoal = dailygoal,
@bufferstock = dailygoal * leadtime
FROM CTE;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anuj Sharma |
| Solution 2 |
