在SQL中重复循环?

时间:2018-10-28 17:20:19

标签: sql

如何重复一些SQL语句直到出现条件

    repeat                    
    SQL statement             
    ......                    
    until condition           

select count(*) as Total from  Table
                                  _____________
    repeat                                     |
        total = result                         | how replace repeat and 
        R1 as (select total*20/100 from Table) | Until condition with an 
        R2 as (select total*20/100 from Table) | SQL statement 
        R3 as (select total*60/100 from Table) | how can i loop this code
        result =R1+R2+R3                       |
    until result = total          _____________|

2 个答案:

答案 0 :(得分:0)

如果您谈论的是 MS-SQL Server ,则可以使用WHILE

WHILE Boolean_expression   
     { sql_statement | statement_block | BREAK | CONTINUE }

来自MSDN的示例:

USE AdventureWorks2012;  
GO  
WHILE (SELECT AVG(ListPrice) FROM Production.Product) < $300  
BEGIN  
   UPDATE Production.Product  
      SET ListPrice = ListPrice * 2  
   SELECT MAX(ListPrice) FROM Production.Product  
   IF (SELECT MAX(ListPrice) FROM Production.Product) > $500  
      BREAK  
   ELSE  
      CONTINUE  
END  
PRINT 'Too much for the market to bear';    

答案 1 :(得分:0)

纯标准SQL中唯一的迭代构造是“递归CTE”。除此之外,没有其他方法。

现在,如果您正在谈论PL / SQL,PLpg / SQL或TSQL之类的过程和功能,那么有很多不同的解决方案。