我正在尝试执行一条if语句,该语句需要在查询的From子句中完成。但是,当我尝试这样做时,我得到了这个错误
关键字'THEN‘附近的语法不正确。
我尝试使用的查询如下:
SELECT *
FROM
--a few tables with joins
IF (@a IS NULL OR @a <> '') THEN
--perform a few more joins
WHERE
--rest of query
从from子句执行case或if语句是不可能的吗?
发布于 2018-03-08 10:28:53
在意识到我不能使用IF语句后,Case会更合适,我已经阅读了,这只能动态地完成,而不是从SQL本身。
发布于 2018-03-08 10:34:35
你不能在基础层面上做到这一点。当您编写查询时,您已经知道它将返回什么数据,以及需要哪些表来获取这些数据。
现在,您可以通过使用outer join
以及ISNULL()
和COALESCE()
等语句在连接中的表之间进行一些切换,以查看连接的表是否确实包含我们正在寻找的数据。
joins可能看起来像这样:
declare @checkthis int
select @checkthis = (whatever, resulting in a 1 or a 0)
select *
from tbl_a as a
left outer join tbl_b as b -- tbl_b is optional if @checkthis is 1, else ignore it
on a.b_foreign_key = b.primary_key and @checkthis = 1
发布于 2018-03-08 11:05:59
根据您的joins,您可以这样做...
DECLARE @Join AS BIT
SET @Join = 1 --Performs inner join
SET @Join = 0 --ignores join
SELECT *
FROM Table1 a
LEFT JOIN Table2 b
ON a.Id = b.Id
WHERE
((@Join = 0) OR (@Join = 1 AND b.Id IS NOT NULL))
https://stackoverflow.com/questions/49170663
复制相似问题