使用While循环来计算表中的值?

时间:2013-03-01 11:36:12

标签: sql sql-server stored-procedures

我有一个下表我需要循环记录并将值添加到变量

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

谢谢大家

3 个答案:

答案 0 :(得分: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))为记录提供序数,但不会改变排序。

答案 1 :(得分:1)

问题在于这一行:

SET @Variable1= Variable1+1

不起作用,将其更改为:

SET @Variable1= @Variable1+1

如果您要离开它,您应该收到此错误:

Msg 207, Level 16, State 1, Line 11
Invalid column name 'Variable1'.

答案 2 :(得分:1)

这也适用(根据您的要求):

Fiddle demo here

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)