Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set variable in to Ms Sql select

Tags:

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
like image 750
valisimo Avatar asked May 27 '11 12:05

valisimo


People also ask

Can I use a variable in an SQL statement?

You can use variable objects in an SQL query as well as string values.

Can we use set with SELECT in SQL?

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.

Can we use set in SELECT?

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.


1 Answers

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
like image 139
KenL Avatar answered Sep 22 '22 17:09

KenL