我需要优化动态SQL。我需要使CASE Expression Dynamic。我有一份ATTRIBUTE_LIST& amp; SCENARIO_LIST,如下所示。我写了一个函数来动态地获取它们。如何替换三个CASE Expression并使其成为动态?我试图避免硬编码。
SET @ATTRIBUTE_LIST = 'symbol_type, currency, performing_status' -- INPUTS
SET @SCENARIO_LIST = 'historicalsimulation_1day_end_10dec2013, historicalsimulation_1day_end_11dec2013'
SELECT CASE
WHEN (GROUPING(Scenario_Name) = 1) THEN ''ALL''
WHEN (Scenario_Name = ''[BaseCase]'') THEN ''BaseCase''
ELSE ISNULL(Scenario_Name, '''')
END AS Scenario_Name,
CASE
WHEN (GROUPING(Symbol_Type) = 1) THEN ''ALL''
ELSE ISNULL(Symbol_Type, '''')
END AS Symbol_Type,
CASE
WHEN (GROUPING(Currency) = 1) THEN ''ALL''
ELSE ISNULL(Currency, '''')
END AS Currency,
CASE
WHEN (GROUPING(Performing_Status) = 1) THEN ''ALL''
ELSE ISNULL(Performing_Status, '''') \
END AS Performing_Status,
SUM(Value) AS ScenarioValue
FROM [20151005_171003_UserName_NT-22_Analysis_Tue] o
LEFT JOIN [20151005_171003_UserName_NT-22_Analysis_Tue_Position_Data] pld
ON o.Position_Unique_Identifier=pld.Position_Unique_Identifier
GROUP BY ' + @ATTRIBUTE_LIST + ' WITH CUBE) AS DATA
PIVOT ( Sum(scenariovalue)
FOR scenario_name IN (' + @SCENARIO_LIST + ')'
答案 0 :(得分:0)
您似乎正在使用SQL Server。这是循环遍历您的属性并构建一系列case
表达式的强力方法:
declare @cases nvarchar(max) = '';
declare @l varchar(max) = @ATTRIBUTE_LIST + ',';
declare @ofs int = 0;
declare @pos int = charindex(',', @l, @ofs + 1);
while @pos > 0
begin
if @cases <> '' set @cases = @cases + ',';
set @cases = @cases +
replace('
CASE WHEN (GROUPING(<COL>) = 1) THEN ''ALL''
ELSE ISNULL(<COL>, '''')
END AS <COL>',
'<COL>', substring(@l, @ofs + 1, @pos - @ofs - 1)
);
set @ofs = @pos;
set @pos = charindex(',', @l, @ofs + 1);
end
select @cases;