0

我有一个下表,我需要遍历记录并将值添加到变量

Declare @Variable1 INT
SET @Variable1=0

Declare @totalval INT
SET @totalval=0

While (@Variable1<=20)
BEGIN
SET @totalval=@totalval+(Select Salary from EmpTable Where EmpID=9)
PRINT @totalval
SET @Variable1= Variable1+1
END
GO

我无法打印值...我使用的是 SQL Server 2005

谢谢你们

4

3 回答 3

2

你可以改用这个:

;WITH a AS
(
    SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT 0)) num
            , *
    FROM    EmpTable
    WHERE   EmpID = 9

)

SELECT  @totalval = SUM(Salary)
        , @Variable1 = COUNT(*)
FROM    a 
WHERE   num <= 20

这将是执行此类任务的常用方法之一,并且比循环更有效。ROW_NUMBER() OVER (ORDER BY (SELECT 0))为记录提供序数但不改变排序。

于 2013-03-01T11:43:51.777 回答
1

问题是这一行:

SET @Variable1= Variable1+1

这不起作用,将其更改为:

SET @Variable1= @Variable1+1

如果你要离开它,你应该得到这个错误:

Msg 207, Level 16, State 1, Line 11
Invalid column name 'Variable1'.
于 2013-03-01T11:41:15.797 回答
1

这也有效(根据您的要求):

小提琴演示在这里

declare @total int, @records int = 20 

select top( @records) @total=isnull(@total,0) + salary
from EmpTable
where empid = 9
-- order by salary (you may need to order by something)
于 2013-03-01T11:57:45.520 回答