开发者

nested SQL Stored proc while not looping

开发者 https://www.devze.com 2023-01-12 08:15 出处:网络
I am trying to generate a set of rows for a matrix but the @xcolcount only does on loop staying at zero while the inner loop does what it needs to:

I am trying to generate a set of rows for a matrix but the @xcolcount only does on loop staying at zero while the inner loop does what it needs to:

 Declare @xColCount int
 Declare @yRowCount int
 set @xCo开发者_Go百科lCount = 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


I think you only just need to reset your inner counter back to zero inside the outer loop - I moved the SET @yRowCount = 0 into the outer loop:

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

With your code, once the inner loop completed, the @yRowCount was at @heightRow and never got reset - so the inner loop (and thus the INSERT statement) never executed anymore.


If you use a numbers table starting at zero, this becomes one set based statement

;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;
0

精彩评论

暂无评论...
验证码 换一张
取 消