1

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....

1
  • 1
    Solution will most likely depend on which concrete database system you're using; SQL is just the query language, not a database system. Please add whatever you're using as a tag to your question: MySQL, DB2, Oracle, SQL Server, Postgres or whatever else that might be .... Commented Jan 30, 2014 at 11:52

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.