在从表中动态选择/连接值的最简单方法上苦苦挣扎

时间:2016-04-13 07:25:19

标签: sql-server dynamic-sql

我有一个变量和值表,我将知道要选择哪些参数代码。该表将动态更改。

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的parmetercode,而来自#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 

1 个答案:

答案 0 :(得分:1)

<强> UPD 即可。首先,我忘了内心选择。

其次,你仍然试图用单引号包装整个in条件。你需要

or ParameterCode in ('value1', 'value2', 'value3')

,但你这样做

or ParameterCode in ('value1, value2, value3') -- look at quotes

第三,您将where置于每个or条件

where ParameterCode1 in (...)
or where ParameterCode2 in (...)
or where ParameterCode3 in (...)

@whereCondition字符串构造中删除它并完成您的查询,就像我在@selectQuery变量中所做的那样。

我认为您可以使用真正的动态SQL查询,即动态构建查询然后执行它(查看下面代码片段中的注释以获取更多信息):

declare
    @whereConditions nvarchar(max) = stuff((
    -- here we create where conditions as
    --   paramCode in (itsValues) 
    --   or anotherParamCode in (anotherItsValues) etc.
    select
        'or ' + ParameterCode + ' in (' + [Values] + ') 
        '
    from (
        -- here we create output with two columns: parameter code and
        -- all values associated with that code separated by comma
        select distinct
            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 = 'Treatment'
                and table_schema ='AnalyticsDW'
        )
    ) conditions
    FOR XML PATH ('') -- !!! this one
), 1, 3, '')

declare
    @selectQuery nvarchar(max) = N'
select
    *
from AnalyticsDW.Treatment
where
    ' + @whereConditions

print @selectQuery
exec sp_executesql @selectQuery