简体   繁体   English

SQL根据变量插入多行

[英]SQL Insert Multiple Rows Based On Variable

I have a variable @RowNumber 我有一个变量@RowNumber

I would like to create a variable table @table based on the @RowNumber variable. 我想基于@RowNumber变量创建一个变量表@table

If @RowNumber is 6 I would like the @table top present the following information 如果@RowNumber为6,我希望@table top呈现以下信息

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

Any help will be greatly appreciated.... 任何帮助将不胜感激....

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

In SQL Server: 在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

One way in SQL Server for a table T : 在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM