如何修改该sql——在存储过程中利用循环来求和
我想要的是:在存储过程中利用循环来求0-50的和。
请问该存储过程应该如何修改?
CREATE PROCEDURE pro_Sum
@addend int
AS
BEGIN
Declare @sql nvarchar(225)
Declare @n int
Declare @Sum int
set @n=0
while @n<@addend
begin
set @sql='@sum=@Sum+@addend'
exec(@sql)
set @n=@n+1
end
END
execute pro_Sum 50;
------解决方案--------------------纯粹你的需求,这样就可以了:
SELECT SUM(number)
FROM master..spt_values
WHERE number BETWEEN 0 AND 50
AND type = 'p'
------解决方案--------------------
create PROCEDURE pro_Sum @addend INT
AS
BEGIN
DECLARE @sql NVARCHAR(225)
DECLARE @n INT
DECLARE @Sum INT
SET @n = 0
SET @Sum=0
WHILE @n < @addend
BEGIN
SET @Sum=@Sum+@n
SET @n = @n + 1
END
PRINT @Sum
PRINT @n
SELECT @Sum
END
go
EXEC pro_Sum 50
/*1225*/
------解决方案--------------------DECLARE @i int,@Sum int
set @i=1
SET @Sum=0
WHILE @i<50
BEGIN
SET @Sum=@Sum+@n
SET @i= @i + 1
END
PRINT @Sum