在动态 where 子句中使用子查询
Using a subquery in a dynamic where clause
我正在尝试执行以下操作:
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)
这将始终 return:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
有人知道我如何在没有 if 和重复查询的情况下实现这一点吗?
我认为您根本不需要子查询,只需使用带有 WHERE
子句的 JOIN
:
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
。
Has anybody an idea how I can realize this without an if and repeating
the query?
这样的东西可能适合你。
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
);
为了详细说明@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无关。
你可以试试这个;
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))
</pre>
我正在尝试执行以下操作:
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)
这将始终 return:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
有人知道我如何在没有 if 和重复查询的情况下实现这一点吗?
我认为您根本不需要子查询,只需使用带有 WHERE
子句的 JOIN
:
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
。
Has anybody an idea how I can realize this without an if and repeating the query?
这样的东西可能适合你。
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
);
为了详细说明@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无关。
你可以试试这个;
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))
</pre>