Can I loop through a table variable in T-SQL?

后端 未结 11 636
轮回少年
轮回少年 2020-12-04 07:47

Is there anyway to loop through a table variable in T-SQL?

DECLARE @table1 TABLE ( col1 int )  
INSERT into @table1 SELECT col1 FROM table2

11条回答
  •  臣服心动
    2020-12-04 08:22

    look like this demo:

    DECLARE @vTable TABLE (IdRow int not null primary key identity(1,1),ValueRow int);
    
    -------Initialize---------
    insert into @vTable select 345;
    insert into @vTable select 795;
    insert into @vTable select 565;
    ---------------------------
    
    DECLARE @cnt int = 1;
    DECLARE @max int = (SELECT MAX(IdRow) FROM @vTable);
    
    WHILE @cnt <= @max
    BEGIN
        DECLARE @tempValueRow int = (Select ValueRow FROM @vTable WHERE IdRow = @cnt);
    
        ---work demo----
        print '@tempValueRow:' + convert(varchar(10),@tempValueRow);
        print '@cnt:' + convert(varchar(10),@cnt);
        print'';
        --------------
    
        set @cnt = @cnt+1;
    END
    

    Version without idRow, using ROW_NUMBER

        DECLARE @vTable TABLE (ValueRow int);
    -------Initialize---------
    insert into @vTable select 345;
    insert into @vTable select 795;
    insert into @vTable select 565;
    ---------------------------
    
    DECLARE @cnt int = 1;
    DECLARE @max int = (select count(*) from @vTable);
    
    WHILE @cnt <= @max
    BEGIN
        DECLARE @tempValueRow int = (
            select ValueRow 
            from (select ValueRow
                , ROW_NUMBER() OVER(ORDER BY (select 1)) as RowId 
                from @vTable
            ) T1 
        where t1.RowId = @cnt
        );
    
        ---work demo----
        print '@tempValueRow:' + convert(varchar(10),@tempValueRow);
        print '@cnt:' + convert(varchar(10),@cnt);
        print'';
        --------------
    
        set @cnt = @cnt+1;
    END
    

提交回复
热议问题