日期:2014-05-18  浏览次数:20638 次

请教WHILE循环,输出1+N的结果,不用插入临时表
WHILE循环,输出1+N的结果,本人水平有限,直接用WHILE无法得到最终的结果,只能插入临时表,然后SELECT SUM临时表。
请教各位大神,不用临时表,能否做到呢!
SQL code

CREATE TABLE #TEST(SHUZI INT)

declare @A int,
        @B INT
SET @A=1
SET @B=100
PRINT @A
WHILE @A<=@B
    BEGIN 
INSERT INTO #TEST VALUES(@A)
SET @A=@A+1
END

SELECT * FROM #TEST
SELECT sum(SHUZI) FROM #TEST


------解决方案--------------------
SQL code
declare @A int,
        @B INT,
        @ssum int
SET @A=1
SET @B=100
set @ssum=0
PRINT @A
WHILE @A<=@B
    BEGIN 
 set @ssum=@ssum+@a
SET @A=@A+1
END
 print @ssum

------解决方案--------------------
SQL code

DECLARE @A INT
DECLARE @Total INT

SET @A = 1
SET @Total = 0
WHILE @A < 101
BEGIN
    SET @Total = @Total + @A
    SET @A = @A + 1
END

SELECT @Total

------解决方案--------------------
SQL code

declare @A int,
        @B INT,
        @Sum int
SET @A=1
SET @B=100
set @sum=0
PRINT @A
WHILE @A<=@B
    BEGIN 
        SET @A=@A+1
        SET @Sum=@Sum+@A
    END


SELECT  @Sum

------解决方案--------------------
[code=SQL]
--CREATE TABLE #TEST(SHUZI INT)
--
--declare @A int,
-- @B INT
--SET @A=1
--SET @B=100
--PRINT @A
--WHILE @A <=@B
-- BEGIN
--INSERT INTO #TEST VALUES(@A)
--SET @A=@A+1
--END
--
--SELECT * FROM #TEST
--SELECT sum(SHUZI) FROM #TEST


declare @B INT
SET @B=100

;WITH c AS(
SELECT 1 AS Row
UNION ALL
SELECT Row+1 AS Row FROM c
WHERE c.Row <@B

)
SELECT SUM(Row) FROM c
[/code]