views:

19

answers:

2

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 @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
+2  A: 

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.

marc_s
im not so bright............... thanks
@user401217: sometimes you're just so deep into your code, you can't see the most obvious mistakes anymore. Happens to everyone once in a while, I guess ;-)
marc_s
A: 

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