根据条件在SQL中创建变量?

时间:2019-05-15 05:08:19

标签: sql tsql sql-server-2008

您可以根据条件在SQL Server中创建变量吗?

例如,我将传递类似'2016,2017'

的字符串

我的查询将创建2个变量,因为它具有2年的时间

现在我是否可以在字符串中传递10年,例如'2010,2011,...'

我的查询也必须创建10个变量...

这有可能吗?

编辑:

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

输出

2014 2015

编辑2

原因:

我想拥有一个可以输出查询到的销售数据的SP,因为我已经问过here如何获取数据,所以我现在被赋予使其动态化的任务,特别是自从保留15年。查询的数据可能是1到15年

我的第一个想法是以字符串的形式传递岁月

exec SP_test '2014,2015,2016'

这使我想到了创建动态变量,以便我可以替换查询中的年份以及创建查询以生成适当结果所需的字符串

完整的伪代码

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

这只是一个示例,但是查询应构建字符串。该示例有2年的时间,因此该查询创建了两个select语句(这是另一个问题,但是我想我可能对此有解决方案),然后是涉及年份的唯一字段。

  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`

1 个答案:

答案 0 :(得分:0)

据我所知,除非您完全动态地创建SQL逻辑并使用{​​{1}}或EXECUTE执行它,否则不可能以这种方式动态生成变量。

您可能会考虑使用临时表或表变量。该表将作为一种数组。

sp_executesql

对不起,请稍作调整。我想发布一个可行的示例(给出您的预期输出)。

附加说明:

如果您还想包含最后一个值,则可能必须在代码中添加更复杂的逻辑...或者您可以在declare @string as nvarchar(max) = '2010,2011,2012,2013,2014,2015,2016'; declare @vars as table ([index] int identity, [value] nvarchar(max)); declare @charindex as int = CHARINDEX(',', @string); declare @value as nvarchar(max); while @charindex > 0 begin set @value = substring(@string, 0, @charindex); set @string = substring(@string, @charindex + 1, LEN(@string)); insert into @vars ([value]) values (@value); set @charindex = CHARINDEX(',', @string); end; select [index], [value] from @vars order by [index]; 值后附加一个逗号...