带有多个过滤器的SQL Server查询

时间:2017-09-28 20:20:37

标签: sql-server stored-procedures inner-join

我正在写3个表" table1"," table2"," tableMap"。基于下拉列表中的选定值。但我没有得到预期的结果。请帮忙。

下拉1:

<Promo Name>
- All - value = ""
- ABC - value = "1"
- XYZ - value = "2"

下拉2:

<Store Type>
- All - value = ""
- Type 1 - value = "1"
- Type 2 - value = "2"

下拉3:

<Store Area>
- All - value = ""
- Area 1 - value = "1"
- Area 2 - value = "2"

表1:

ID | Store Name | Store Address | Store Type | Store Area
---+------------+---------------+------------+-----------
1  | ABC        |  112 test road| Type 1     | Area 1
2  | XYZ        |  22 test2 road| Type 2     | Area 2

表2:

ID | Promo Name  
---+------------
1  | promo 1    
2  | promo 2     

表格地图:

ID | Promo ID   | Store Type | Store Area
---+------------+----------------+------------+-----------
1  | 1          | 2,1        |
2  | 2          |            | 1

[Store Type]和[Store Area]的值是[表1]的ID 因此,在下面的查询中,我们应该将[商店类型] / [商店区域]与[表1]的[ID]进行映射

我正在尝试编写查询,以便根据下拉列表选择值获取结果。

查询:

declare @promoname varchar(255),
        @type varchar(255),
        @area varchar(255)

select  
    t2.Promo Name, t2.ID, t1.Store Name, t1.Store Address
from 
    [Tablemap] tm  
inner join 
    [Table2] t2 on tm.Promo ID = t2.ID
where 
    (@promoname = '' or t2.[promoname] = @promoname)
    and (@type = '' or @type in (select [name] 
                                 from dbo.SplitString (tm.Store Type)))   

结果 - 预期 - (但不使用上述查询,因为我没有在上面添加位置表而不确定如何添加它):

Promo Name | Store Name | Address
-----------+------------+---------------
promo 1    | ABC        | 112 test road
promo 2    | ABC        | 112 test road

1 个答案:

答案 0 :(得分:1)

请尝试以下代码。

declare @promoname varchar(255),
        @type varchar(255),
        @area varchar(255)

select  t2.Promo Name, t2.ID, t1.Store Name, t1.Store Address
from 
    [Tablemap] tm
inner join [Table2] t2 on tm.Promo ID = t2.ID
inner join [Table1] t1 on tm.Promo ID = t1.ID
where (@promoname = '' or t2.[promoname] = @promoname)
    and (@type = '' or t1.[Store Type] in (select [name] from dbo.SplitString (tm.Store Type)))