我的查询将如下所示,我有50个组合(L1,L2,L3 .. L50),具有不同的where子句和不同的列名,
您能否建议我,如何编写简单的方法来实现并缩短处理时间?
L1 A和L1 B colunm名称相同,但L1 C列名称完全不同。与其他级别相似。
Ex:l2 A,L2 B,L2 C,...... L50 A等
Declare @SQL max set @sql = ' SELECT '+@InputColumn+',
19 AS [LEVEL], --- Dynamic column name change
'L1 A' AS NAME , --- Dynamic column name change
BP_GEO AS [GEOGRAPHY],
BP_CTRY AS COUNTRY ,
BP_DIV AS DIVISION,
BP_BU AS BUS ,
BP_BUSINESS AS BU_LC_EC,
BP_SEG_NEW AS SEGMENT ,
FROM #Dummy(NOLOCK)
WHERE BP_SEG_NEW = GCP_SEG_NEW --- Dynamic column name change
UNION ALL
SELECT '+@InputColumn+',
19 AS [LEVEL], --- Dynamic column name change
'L1 B' AS NAME , --- Dynamic column name change
BP_GEO AS [GEOGRAPHY],
BP_CTRY AS COUNTRY ,
BP_DIV AS DIVISION,
BP_BU AS BUS ,
BP_BUSINESS AS BU_LC_EC,
BP_SEG_NEW AS SEGMENT,
FROM #Dummy (NOLOCK)
WHERE BP_SEG_NEW <> GCP_SEG_NEW AND GCP_SEG_NEW = 'KUMAR'-- Unable to pass 2 condition in the where
UNION ALL
SELECT '+@InputColumn+',
19 AS [LEVEL], --- Dynamic column name change
'L1 C' AS NAME , --- Dynamic column name change
GCP_GEO AS [GEOGRAPHY], --- Dynamic column name change
GCP_CTRY AS COUNTRY , --- Dynamic column name change
GCP_DIV AS DIVISION, --- Dynamic column name change
GCP_BU AS BUS , --- Dynamic column name change
GCP_BUSINESS AS BU_LC_EC, --- Dynamic column name change
GCP_SEG_NEW AS SEGMENT, --- Dynamic column name change
FROM #Dummy(NOLOCK)
WHERE BP_SEG_NEW <> GCP_SEG_NEW --- Dynamic column name change
UNION ALL --- level 20
SELECT '+@InputColumn+',
20 AS [LEVEL], --- Dynamic column name change
'L2 A' AS NAME , --- Dynamic column name change
BP_GEO AS [GEOGRAPHY],
BP_CTRY AS COUNTRY ,
BP_DIV AS DIVISION,
BP_BU AS BUS ,
BP_BUSINESS AS BU_LC_EC,
BP_SEG_NEW AS SEGMENT ,
FROM #Dummy(NOLOCK)
WHERE Global = GCP_SEG_NEW --- Dynamic column name change
UNION ALL
SELECT '+@InputColumn+',
20 AS [LEVEL], --- Dynamic column name change
'L2 B' AS NAME , --- Dynamic column name change
BP_GEO AS [GEOGRAPHY],
BP_CTRY AS COUNTRY ,
BP_DIV AS DIVISION,
BP_BU AS BUS ,
BP_BUSINESS AS BU_LC_EC,
BP_SEG_NEW AS SEGMENT,
FROM #Dummy (NOLOCK)
WHERE Global <> GCP_SEG_NEW
AND GCP_SEG_NEW = 'KUMAR'-- Unable to pass 2 condition in the where
UNION ALL
SELECT '+@InputColumn+',
20 AS [LEVEL], --- Dynamic column name change
'L2 C' AS NAME , --- Dynamic column name change
GCP_GEO AS [GEOGRAPHY], --- Dynamic column name change
GCP_CTRY AS COUNTRY , --- Dynamic column name change
GCP_DIV AS DIVISION, --- Dynamic column name change
GCP_BU AS BUS , --- Dynamic column name change
GCP_BUSINESS AS BU_LC_EC, --- Dynamic column name change
GCP_SEG_NEW AS SEGMENT, --- Dynamic column name change
FROM #Dummy(NOLOCK)
WHERE Global <> GCP_SEG_NEW --- Dynamic column name change
EXEC (@sql)
如何在一个select语句中将L1 A,L1 B,L1 C与动态列名和where子句组合?
请参阅示例查询以供参考。
注意:上面的查询只有我给出的一个组合,类似于我有50个组合来编写带有union all的代码。
请帮帮我
由于