I have a variable @RowNumber
I would like to create a variable table @table
based on the @RowNumber
variable.
If @RowNumber
is 6 I would like the @table top present the following information
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:
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
:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.