在where where条件中生成具有可变列号的动态查询

时间:2015-10-30 17:53:14

标签: sql-server

我在SQL SERVER中有一个包含Below Data的表

Key  SCH_NME TBL_NME    COLM_NME
---  ------  -------     ------------- 
PRM  DBO     Test       Col1,col2,col3
FRN  CHK     Tab          Col4,Col5

请给我一个动态查询以获得以下格式的输出

select col1,col2,col3 from DBO.[Test] where (col1 is null OR col2 is null OR col3 is null;)

OR

select col4,col5 from CHK.[Tab] where (col4 is null OR col5 is null)

其中将根据COLM_NME(可变)

填充条件

1 个答案:

答案 0 :(得分:0)

这种设计非常糟糕的尖叫声,但实际的代码非常简单。你需要动态的sql才能工作。我还必须根据您提供的样本数据生成表格。

if OBJECT_ID('tempdb..#Something') is not null
    drop table #Something

create table #Something
(
    MyKey char(3)
    , SCH_NME char(3)
    , TBL_NME varchar(10)
    , COLM_NME varchar(100)
)

insert #Something
select 'PRM', 'DBO', 'Test', 'Col1,col2,col3' union all
select 'FRN', 'CHK', 'Tab', 'Col4,Col5'


--Now for the actual code.

Declare @SQL nvarchar(max)
    , @TblName sysname = 'Test'

select @SQL = 'select ' + COLM_NME + ' from [' + SCH_NME + '].[' + TBL_NME + '] where ' + REPLACE(COLM_NME, ',', ' IS NULL OR ') + ' IS NULL;'
from #Something
where TBL_NME = @TblName

select @SQL
--uncomment below when you are ready to run this
--exec sp_executesql @SQL
相关问题