【发布时间】:2016-04-14 07:28:12
【问题描述】:
我有一个变量和值表,我将知道要选择哪些参数代码。该表将动态更改。
CREATE TABLE #TreatmentTableVariables (ParameterCode VARCHAR(64), Value varchar(64))
INSERT #TreatmentTableVariables VALUES ('TripOriginLocationCode','BGY')
然后我有另一个名为 AnalyticsDW.Treatment 的表,其中有一个名为 TripOriginLocationCode 的列,我想从 AnalyticsDW.Treatment 中选择那些行,其中 TripOriginLocationCode = #TreatmentTableVariables 中的值。
AnalyticsDW.Treatment 的主键为 TreatmentID。
所以我最初是使用动态 SQL 来选择临时表中包含的 TreatmentID 的列
SELECT @Columns = SubString ( ( SELECT + ', ' +'t.' + QUOTENAME(Column_name)
from INFORMATION_SCHEMA.columns c
JOIN #TreatmentTableVariables t ON c.COLUMN_NAME=t.ParameterCode
WHERE Table_name IN ('Treatment','TreatmentProduct') AND TABLE_SCHEMA='AnalyticsDW'
FOR XML PATH ( '' ) ), 1, 1000)
但我正在努力解决如何仅选择 AnalyticsDW.Treatment 的行,其中动态列等于 #TreatmentTableVariables 中的参数代码,而 #TreatmentTableVariables 中的值等于该特定列的观察值。
AnalyticsDW.Treatment 数据示例:
Declare AnalyticsDW.Treatment table
(
TreatmentID varchar(100),
TripOriginLocationCode varchar(100),
TripDestinationLocationCode varchar(100)
)
insert into AnalyticsDW.Treatment values
('1','BRG','SLC'),
('2','AHO','BRG')
目标数据集:
Declare @goal table
(
TripOriginLocationCode varchar(100)
)
insert into @goal values
('BRG')
关于我如何从目标数据集中进行选择的示例(在动态 sql 查询中):
declare @dynamicquery varchar(200)
set @dynamicquery='
select a.*, '+@Columns+' into #CompletePricingtypes2 from #somedataset a
join AnalyticsDW.Treatment t on a.TreatmentID=t.TreatmentID '
编辑:附加信息
declare
@whereConditions nvarchar(max) = stuff((
-- here we create where conditions as
-- paramCode in (itsValues)
-- or anotherParamCode in (anotherItsValues) etc.
select
'or ' + 'where ' +'t.' +ParameterCode + ' in ('+''''+ltrim([Values]) +''''+') '
from (
-- here we create output with two columns: parameter code and
-- all values associated with that code separated by comma
select
t.ParameterCode,
stuff((
select
', ' + [Value]
from #TreatmentTableVariables
where
ParameterCode in (t.ParameterCode)
FOR XML PATH ('')
), 1, 1, '') as [Values]
from #TreatmentTableVariables t
where ParameterCode in (select COLUMN_name from INFORMATION_SCHEMA.columns where Table_name IN ('Treatment') AND TABLE_SCHEMA='AnalyticsDW')
) conditions
), 1, 3, '')
print @whereconditions
编辑:这行得通
select
'or ' + ParameterCode + ' in('+ [Values] +')
'
from (
select distinct
t.ParameterCode,
(
select
', ''' + [Value] + ''''
from #TreatmentTableVariables
where
ParameterCode in (t.ParameterCode)
) as [Values]
from #TreatmentTableVariables t
where ParameterCode in (select
COLUMN_name
from INFORMATION_SCHEMA.columns
where Table_name IN ('Treatment') AND TABLE_SCHEMA='AnalyticsDW')
) conditions
【问题讨论】: