SQL Server存储过程用于动态查询

时间:2017-04-27 02:40:21

标签: sql-server dynamic

我需要一个针对以下动态查询的过程。在该过程中,f_idvalue是输入参数。 f_idvalue是值的集合。

例如

f_id=1780
value=ABC
f_id=22483
value=`sasdfa`
f_id=3334
value=soap

因此,在下面的查询和退出部分将动态添加取决于f_idvalue的数量。

select distinct 
    v1.entity_id 
from 
    values v1 
inner join 
    listings l on v1.entity_id = l.entity_id   
where 
    l.c_id = 83  
    and exists (select 1 from values v2 
                where v1.entity_id = v2.entity_id 
                  and v2.f_id = 1780 and (value = ABC)) 
    and exists (select 1 from values v3 
                where v1.entity_id = v3.entity_id  
                  and v3.field_id = 22483 and (value = sasdfa)) 
    and exists (select 1 from values v4 
                where v1.entity_id = v4.entity_id   
                  and v4.field_id = 3334 and (value = soap)) 
    and exists (select 1 from values v5 
                where v1.entity_id = v5.entity_id  
                  and v5.field_id = 3433 and (value=paste)) 
order by 
    l.id desc

1 个答案:

答案 0 :(得分:0)

您需要创建一个存储过程,其中包含您在问题中提供的SQL作为带参数的SQL字符串,并使用EXEC语句执行SQL字符串。

以下是示例

CREATE PROCEDURE usp_dynamic_sql
(   @f_id AS INT,
    @value AS NVARCHAR(100)
)
AS
BEGIN
    DECLARE @SQL AS NVARCHAR(2000);

    SET @SQL
        =      ('
SELECT distinct 
    v1.entity_id 
from 
    values v1 
inner join 
    listings l on v1.entity_id = l.entity_id   
where 
    l.c_id = 83  
    and exists (select 1 from values v2 
                where v1.entity_id = v2.entity_id 
                  and v2.f_id = ''' + @f_id + ''' and (value = ''' + @value
                + ''')) 
    and exists (select 1 from values v3 
                where v1.entity_id = v3.entity_id  
                  and v3.field_id = 22483 and (value = '''+@value
                + ''')) 
    and exists (select 1 from values v4 
                where v1.entity_id = v4.entity_id   
                  and v4.field_id = 3334 and (value = '''+@value
                + ''')) 
    and exists (select 1 from values v5 
                where v1.entity_id = v5.entity_id  
                  and v5.field_id = 3433 and (value='''+@value+''')) 
order by 
    l.id desc'''
               );
    EXEC (@SQL);
END;

编辑2

这是stackoverflow社区中的链接。 Link 1 Link 2

如果你无法成功,请告诉我。我会帮助你的。