smpa01
smpa01

Reputation: 4282

How to dynamically pass on a scalar value in SQL temp table

I have a current query which is as following

DECLARE @start BIGINT =2019, @end BIGINT =2020

DECLARE @yeartable table ( yr BIGINT)

WHILE (@start <= @end)
BEGIN
    INSERT INTO @yeartable
        SELECT @start

    SET @start = @start + 1
END

All I want to do is to pass on the @start and @end values dynamically from another query

For @start I will use

 SELECT MIN(fiscal_year)
 FROM a.b

For @end I will use

SELECT MAX(fiscal_year)
FROM a.b

Is this possible at all? Thank you in advance.

Upvotes: 0

Views: 109

Answers (2)

smpa01
smpa01

Reputation: 4282

I guess I found the answer

        DECLARE 
@start BIGINT =(SELECT MIN(fiscal_year)
FROM
a.b), 
@end BIGINT = (SELECT MAX(fiscal_year) 
FROM
a.b])

DECLARE @yeartable table ( yr BIGINT)

while (@start <= @end)
begin
    insert into @yeartable
    select @start

    set @start = @start+1
end

Upvotes: 1

iceblade
iceblade

Reputation: 641

You can assign the variables this way:

SELECT @start = MIN(fiscal_year)
    FROM a.b

SELECT @end = MAX(fiscal_year)
    FROM a.b

Upvotes: 0

Related Questions