How can I set in MS Sql select variables, idea looks like this:
Declare @var int
SET @var = 0;
Select (if(idid = @var) then sum+1 else sum-1) AS Sum,
set @var = id
FROM table
Edit based on comments.
DECLARE @T TABLE
(
ID INT PRIMARY KEY,
IDID INT,
SUMM INT
)
INSERT INTO @T
SELECT 1,1,4 UNION ALL
SELECT 2,1,5 UNION ALL
SELECT 3,2,6 UNION ALL
SELECT 4,2,7 UNION ALL
SELECT 5,3,8
In select result I need:
ID IDID SUMM
-- ---- ----
1 1 4
2 1 0
3 2 6
4 2 0
5 3 8
You can use variable objects in an SQL query as well as string values.
There are two ways to assign a value to a local variable created previously: SET and SELECT. We can usually use SET and SELECT alternatively without any effect.
SET is the ANSI standard for variable assignment, SELECT is not. SET can only assign one variable at a time, SELECT can make multiple assignments at once. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error.
Is this what you are trying to do?
Declare @var int, @id int
SET @var = 0
SELECT @id = id FROM Table t
if(@id = @var)
BEGIN
SET @var = @var + 1
END
ELSE
BEGIN
SET @var = @var - 1
END
print @var
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