当前位置: 代码迷 >> Sql Server >> 请问WHILE循环,输出1+N的结果,不用插入临时表
  详细解决方案

请问WHILE循环,输出1+N的结果,不用插入临时表

热度:80   发布时间:2016-04-27 12:57:19.0
请教WHILE循环,输出1+N的结果,不用插入临时表
WHILE循环,输出1+N的结果,本人水平有限,直接用WHILE无法得到最终的结果,只能插入临时表,然后SELECT SUM临时表。
请教各位大神,不用临时表,能否做到呢!
SQL code
CREATE TABLE #TEST(SHUZI INT)declare @A int,        @B INTSET @A=1SET @B=100PRINT @AWHILE @A<[email protected]    BEGIN INSERT INTO #TEST VALUES(@A)SET @[email protected]+1ENDSELECT * FROM #TESTSELECT sum(SHUZI) FROM #TEST


------解决方案--------------------
SQL code
declare @A int,        @B INT,        @ssum intSET @A=1SET @B=100set @ssum=0PRINT @AWHILE @A<[email protected]    BEGIN  set @[email protected][email protected]SET @[email protected]+1END print @ssum
------解决方案--------------------
SQL code
DECLARE @A INTDECLARE @Total INTSET @A = 1SET @Total = 0WHILE @A < 101BEGIN    SET @Total = @Total + @A    SET @A = @A + 1ENDSELECT @Total
------解决方案--------------------
SQL code
declare @A int,        @B INT,        @Sum intSET @A=1SET @B=100set @sum=0PRINT @AWHILE @A<[email protected]    BEGIN         SET @[email protected]+1        SET @[email protected][email protected]    ENDSELECT  @Sum
------解决方案--------------------
[code=SQL]
--CREATE TABLE #TEST(SHUZI INT)
--
--declare @A int,
-- @B INT
--SET @A=1
--SET @B=100
--PRINT @A
--WHILE @A <[email protected]
-- BEGIN
--INSERT INTO #TEST VALUES(@A)
--SET @[email protected]+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]
  相关解决方案