【问题标题】:nested SQL Stored proc while not looping嵌套 SQL 存储过程而不循环
【发布时间】:2011-04-02 03:05:02
【问题描述】:

我正在尝试为矩阵生成一组行,但 @xcolcount 仅在循环中保持为零,而内部循环执行所需的操作:

 Declare @xColCount int
 Declare @yRowCount int
 set @xColCount = 0
 set @yRowCount = 0

WHILE (@xColCount < @widthCol) 
BEGIN
    WHILE (@yRowCount < @heightRow)
    BEGIN
      -- do the insert
       INSERT     
         INTO Scenario.MapCell(Guid, Map, Col, ColAplha, Row)
       VALUES (newID(),  @mapGuid, @xColCount, 'A', @yRowCount)

       SET @yRowCount =  @yRowCount + 1
    END

    SET @xColCount =  @xColCount + 1
END

【问题讨论】:

    标签: sql loops while-loop procedure


    【解决方案1】:

    我认为您只需要在外循环内将内部计数器重置为零 - 我将 SET @yRowCount = 0 移动到外循环:

    DECLARE @xColCount int
    DECLARE @yRowCount int
    
    SET @xColCount = 0
    
    WHILE (@xColCount < @widthCol) 
    BEGIN
        SET @yRowCount = 0
    
        WHILE (@yRowCount < @heightRow)
        BEGIN
           -- do the insert
           INSERT INTO Scenario.MapCell(Guid, Map, Col, ColAplha, Row)
             VALUES(newID(), @mapGuid, @xColCount, 'A', @yRowCount)
    
           SET @yRowCount =  @yRowCount + 1
        END
    
        SET @xColCount =  @xColCount + 1
    END
    

    使用您的代码,一旦内部循环完成,@yRowCount 就位于@heightRow 并且永远不会被重置 - 因此内部循环(以及 INSERT 语句)不再执行。

    【讨论】:

    • @user401217:有时您对代码的了解如此之深,以至于您再也看不到最明显的错误了。我猜每个人都会偶尔发生一次;-)
    【解决方案2】:

    如果您使用从零开始的numbers table,这将成为一个基于集合的语句

    ;WITH
      cX AS (SELECT Num AS xColCount FROM NumTable WHERE Num <= @widthCol),
      cY AS (SELECT Num AS yRow  Count FROM NumTable WHERE Num <= @heightRow)
    INSERT Scenario.MapCell(Guid, Map, Col, ColAplha, Row)
    SELECT
        @mapGuid, xColCount, 'A', yRowCount
    FROM
        cX CROSS JOIN cY;
    

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 2012-05-05
      • 1970-01-01
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多