我如何设置MS sql中的select变量,想法如下所示:
Declare @var int SET @var = 0; Select (if(idid = @var) then sum+1 else sum-1) AS Sum,set @var = id FROM table
根据评论编辑.
DECLARE @T TABLE ( ID INT PRIMARY KEY,IDID INT,SUMM INT ) INSERT INTO @T SELECT 1,1,4 UNION ALL SELECT 2,5 UNION ALL SELECT 3,2,6 UNION ALL SELECT 4,7 UNION ALL SELECT 5,3,8
在选择结果我需要:
ID IDID SUMM -- ---- ---- 1 1 4 2 1 0 3 2 6 4 2 0 5 3 8
解决方法
这是你想要做的吗?
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