FROM子句取决于变量值

时间:2015-09-15 11:08:46

标签: sql-server case

我有两个具有相同列名的表,我想根据一个参数值从一个或另一个获取数据。想到的是

的内容
ALTER PROCEDURE [dbo].[traxs_SyncLists_Locations_Search]

    @session_id varchar(30),
    @get_value int,
    @predicate varchar(50),
    @combo varchar(30)

AS

    SELECT
        L.id AS id, 
        L.location AS value
    FROM
        CASE 
            WHEN @combo = 'box' THEN vw_WarehouseLocationBox
            WHEN @combo = 'bay' THEN vw_WarehouseLocationBay
        END L
            LEFT JOIN traxs_temp..__LocationsSyncLists T ON T.session_id = @session_id AND T.id = L.id
    WHERE
        L.whse_no = @get_value AND
        ISNULL(T.archive, 1) = 1 AND
        L.location LIKE @predicate + '%'

这不是正确的SQL语法。经过一些研究,我写了

SELECT 
    L.id AS id, 
    L.location AS value
FROM
    vw_WarehouseLocationBox L
        LEFT JOIN traxs_temp..__LocationsSyncLists T ON T.session_id = @session_id AND T.id = L.id
WHERE
    @combo = 'box' AND -- TRICK
    L.whse_no = @get_value AND
    ISNULL(T.archive, 1) = 1 AND
    L.location LIKE @predicate + '%'
UNION
SELECT 
    L.id AS id, 
    L.location AS value
FROM
    vw_WarehouseLocationBay L
        LEFT JOIN traxs_temp..__LocationsSyncLists T ON T.session_id = @session_id AND T.id = L.id
WHERE
    @combo = 'bay' AND -- TRICK
    L.whse_no = @get_value AND
    ISNULL(T.archive, 1) = 1 AND
    L.location LIKE @predicate + '%'

但我总是对复制一些代码感到不舒服。它只有2个表,但如果它是10个表(可能),如果我复制10次呢?或者我应该使用动态SQL,即使我看到很多人建议反对它?

2 个答案:

答案 0 :(得分:2)

你可以分开可变和不可变的部分。 Mutable将包含基本表的UNION和不可变的 - 其他代码。可能它是重复和动态SQL之间的妥协。

WITH L AS (
    SELECT 
        id AS id, 
        location AS value,
        whse_no,
        'box' AS combo
    FROM vw_WarehouseLocationBox
    UNION ALL
    SELECT 
        id, 
        location,
        whse_no,
        'bay'
    FROM vw_WarehouseLocationBay
)
SELECT 
    id,
    value
FROM L
LEFT JOIN traxs_temp..__LocationsSyncLists T ON T.session_id = @session_id AND T.id = L.id
WHERE
    @combo = combo AND
    L.whse_no = @get_value AND
    ISNULL(T.archive, 1) = 1 AND
    L.location LIKE @predicate + '%'

答案 1 :(得分:1)

结构类似于typeof,其中WarehouseLocation是泛型类型,Box,Bay等是扩展类型。

您的查询似乎只需要通用信息。如果您有权这样做,我会在前两个视图vw_WarehouseLocation之上创建一个视图,并在此处使用您已识别的union方法维护组合逻辑,但包含一个额外的字段“whse_type”来标识typeof。

create view [vw_WarehouseLocation]
as

select
      [id] as [id]
    , [location] as [location]
    , [whse_no] as [whse_no]
    , 'bay' as [whse_type]
from [vw_WarehouseLocationBay]

union all

select
      [id] as [id]
    , [location] as [location]
    , [whse_no] as [whse_no]
    , 'box' as [whse_type]
from [vw_WarehouseLocationBox]

现在,您不仅可以在当前的SP中加入此视图,还可以在不重复逻辑的情况下将任何其他对象加入此视图,即使它在视图中看起来似乎不实用且重复。这种方法更加符合“以可支持的方式修补设计”。

如,

select
      L.id
    , L.location
from vw_WarehouseLocation L
left join traxs_temp..__LocationsSyncLists T
    on T.id = L.id
where L.[whse_type] = @combo