具有可变数量的表连接的动态SQL

时间:2012-12-04 18:13:10

标签: sql sql-server sql-server-2008 tsql dynamic

我的表icdClm是包含人口统计信息的表格与另一个表格之间的联结表格,该表格列出了与该人员相关的各种感兴趣的代码。我希望能够连续多次加入这些表格。我对这段关系中涉及的另一张桌子不感兴趣,因为此时的简单。我想要一个while loop来帮助生成查询(如果有更好的方式我可以使用不同的实现。)

如果查询要运行两次(两个派生表的两次),则下面是所需的输出。

select distinct x1.patid
from
(
select ic.patid
    from icdClm as ic
    where ic.icd like '123%'
) x1 inner join 
(
select ic.patid
    from icdClm as ic
    where ic.icd like '456%'
)x2 on x1.patid=x2.patid
inner join 
(
select ic.patid
    from icdClm as ic
    where ic.icd like '789%'

) x3 on x1.patid=x3.patid

请注意,派生表的别名每次增加1。现在为我的代码。此代码不会生成错误,但我让它运行超过10分钟,但尚未返回任何结果。最后,我想创建另一个依赖于这个存储过程的存储过程,它会询问您所需的派生表的数量,然后使用从用户输入的参数填充where ic.icd like '123%',但首先要做的是:什么不起作用使用以下查询?

declare 
@x int
,@y int
,@sql nvarchar(1000)

select 
@x=1
,@y=3
,@sql =
'select distinct x1.patid
from
(
select ic.patid
    from icdClm as ic
    where ic.icd like ''123%''
) x1'
while @x < @y
begin;
set @sql=@sql+ 
'inner join 
(
    select ic.pati
    from icdClm as ic
    where ic.icd like ''456%''
) x1 on x'+CAST(@y as CHAR(10))+'.patid=x1.patid'
set @y=@y+1
end;
print @sql

2 个答案:

答案 0 :(得分:2)

while @x < @y
begin;

set @y=@y+1
end;

@y是递增的,所以这个循环将永远不会执行(因为y小于x)或者它将是一个无限循环*因为@y总是大于{{1} }

也许你的意思是@x

*你最终可能会得到整数溢出

答案 1 :(得分:2)

看起来你想要做多个术语的条件 如果您使用Intersect,则不需要唯一的名称 我这样做但是我用C#构建它。
很抱歉缺少SP示例。

select patid
    from icdClm 
    where icd like '123%'
Intersect
select patid
    from icdClm 
    where icd like '456%' 

EXCEPT and INTERSECT (Transact-SQL)

我发现Intersect很有效率 有超过5个连接我遇到问题,查询优化器得到了我称之为防御性并且使用我的数据产生了较差的响应时间。
Intersect以蛮力的方式一次完成一次,这可能对您的数据有益,也可能不利 由于你的喜欢在开头没有外卡,它可能会使用索引。