Can you create variables based on condition in SQL server?
for example I will pass a string like '2016,2017'
My query will create 2 variables because it has 2 years
now if I pass 10 years in the string e.g '2010,2011,...'
My query must create 10 variables too...
Is this even possible?
EDIT:
PSEUDOCODE
declare @string as nvarchar(max) = '2014,2015,2016'
declare @count as int = (select LEN(REPLACE(@string, ',', '**')) - LEN(@string) )
while @count <> 0
begin
--create variable statement here
Declare @var + @count as nvarchar(max)
set @string = (select substring(@string,0,CHARINDEX(',', @string)))
set @var +@count = @string
set @count = count - 1
end
select @var1, @var2
OUTPUT
2014 2015
EDIT 2
Reason:
I want to have a SP that will output inquired data of sales, since I already asked here on how could I get the data, I was now tasked to make it dynamic, specially the years since we have a 15 year retention. The inquired data might be from 1 to 15 years
My first idea is passing the years as a string
exec SP_test '2014,2015,2016'
which made me think of creating dynamic variables so I can substitute the years on my query, along with creating strings required by the query to produce the appropriate result
Complete psuedo code
declare @string as nvarchar(max) = '2014,2015,2016'
declare @count as int = (select LEN(REPLACE(@string, ',', '**')) - LEN(@string) )
while @count <> 0
begin
--create variable statement here
Declare @var + @count as nvarchar(max)
set @string = (select substring(@string,0,CHARINDEX(',', @string)))
set @var +@count = @string
set @count = count - 1
end
--up to this point lets say I have created @var1 and @var2
SELECT Item,Price,Quantity,PriceYear,QuantityYear INTO TempFinal
FROM (
SELECT Item,Price,Quantity, 'Price+@var1' as PriceYear,'Quantity+@var1' as QuantityYear FROM @Table+@var1
UNION ALL
SELECT Item,Price,Quantity, 'Price@var2' as PriceYear,'Quantity@var2' as QuantityYear FROM @Table+@var2
) MyTables
This is just an example, but the query should build the strings. The example has 2 years so the query created two select statements (that's another problem, but I think I might have a solution for that) Then the unique fields with the years involved.
SELECT item, SUM([Price+@var1])[Price+@var1],SUM([Quantity+@var1])[Quantity+@var1],SUM([Price+@var2])[Price+@var2],SUM([Quantity+@var2])[Quantity+@var2]
FROM (
SELECT item,Price,Quantity,PriceYear,QuantityYear
FROM TempFinal) up
PIVOT (SUM(Quantity) FOR QuantityYear IN ([Quantity+@var2],[Quantity+@var2]) AS pvt
PIVOT (SUM(Price) FOR PriceYear IN ([Price+@var1],[Price+@var2]) AS pvt2
GROUP by item
ORDER BY item
--do take note that @var1 contains `2014` and @var2 contains `2015`