在动态where子句中使用子查询

时间:2015-02-10 11:31:03

标签: sql-server tsql

我试图执行以下操作:

SELECT *
FROM myTable
WHERE workplace IN
    (CASE @param
        WHEN 'a' THEN (SELECT workplace 
                      FROM workPlaceTable
                      WHERE condition1)
        WHEN 'b' THEN (SELECT workplace 
                      FROM workPlaceTable
                      WHERE condition2)
    END)

这将始终返回:

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

有没有人知道如何在没有if并重复查询的情况下实现这一点?

4 个答案:

答案 0 :(得分:4)

我认为您根本不需要子查询,只需使用带有JOIN子句的WHERE

SELECT T1.*
FROM myTable T1
INNER JOIN workPlaceTable T2 ON T1.workplace = T2.workplace
WHERE (@param = 'a' AND condition1) OR (@param = 'b' AND condition2) 

如果@param = 'a'将评估condition1,否则将评估condition2

答案 1 :(得分:2)

  

有没有人知道如何在没有if和重复的情况下实现这一点   查询?

这样的事情对你有用。

select *
from myTable
where @Param = 'a' and workplace in (
                                    select workplace 
                                    from workPlaceTable
                                    where condition1
                                    ) or
      @Param = 'b' and workplace in (
                                    select workplace 
                                    from workPlaceTable
                                    where condition2
                                    );

答案 2 :(得分:0)

要详细说明@ Allan的回答,联接看起来像这样:

SELECT myTable.*
FROM myTable
INNER JOIN workPlaceTable ON myTable.workplace = workPlaceTable.workplace AND
(
    (@param = 'a' AND <<condition1>>) OR (@param = 'b' AND <<condition2>>)
)

顺便说一句,这个问题与dynamic-sql无关。

答案 3 :(得分:0)

你可以试试这个;


SELECT *
  FROM myTable
 WHERE (@param = 'a' and
       workplace in
       (SELECT workplace FROM workPlaceTable WHERE condition1))
    OR (@param = 'b' and
       workplace in
       (SELECT workplace FROM workPlaceTable WHERE condition2))