SQL插入基于变量的多行

时间:2014-01-30 11:48:49

标签: sql

我有一个变量@RowNumber

我想基于@table变量创建变量表@RowNumber

如果@RowNumber为6,我希望@table顶部提供以下信息

MonthID  Month
1        Month1
2        Month2
3        Month3
4        Month4
5        Month5
6        Month6

任何帮助将不胜感激....

3 个答案:

答案 0 :(得分:1)

declare @rownum int 
declare @monthid int
declare @date datetime

/* rownum initialized in your code*/
select @rownum = 6

select @monthid = 1
select @date = '20140101'

declare @table table ( 
MonthID int null,
MonthName varchar (10) null
);
while ( @rownum > 0 ) 
begin
insert into @table values ( @monthid , datename(month,dateadd(month,@monthid-1,@date)))
select @monthid = @monthid + 1
select @rownum = @rownum - 1
end

答案 1 :(得分:0)

在SQL Server中:

DECLARE @Table TABLE (MonthID int, Month nvarchar(20))
DECLARE @RowNumber int = 12

DECLARE @Count int = 1
WHILE @Count <= @RowNumber
BEGIN
    INSERT INTO @Table (MonthID, Month) VALUES (@Count, 'Month' + CAST(@Count AS nvarchar))
    SET @Count = @Count + 1
END

SELECT * FROM @Table

答案 2 :(得分:0)

SQL Server中表T的一种方式:

declare @RowNumber int = 6

;with T(MonthID, Month) as
(
    select 1 as MonthID , 'month' + cast(1 as varchar(6))
        union all
    select MonthID + 1, 'month' + cast(MonthID as varchar(6))
        from T
        where MonthID < @RowNumber
)

select * from T