[英]Is it possible to use a Case statement in a sql From clause
Is it possible to use a Case statement in a sql From clause using SQL 2005? 是否可以使用SQL 2005在sql From子句中使用Case语句? For example, I'm trying something like: 例如,我正在尝试这样的事情:
SELECT Md5 FROM
CASE
WHEN @ClientType = 'Employee' THEN @Source = 'HR'
WHEN @ClientType = 'Member' THEN @Source = 'Other'
END CASE
WHERE Current = 2;
I don't believe that's possible. 我不相信这是可能的。 For one thing, query optimizers assume a specific list of table-like things in the FROM clause. 首先,查询优化器假定FROM子句中特定于表的事物列表。
The most simple workaround that I can think of would be a UNION between the two tables: 我能想到的最简单的解决方法是两个表之间的UNION:
SELECT md5
FROM hr
WHERE @clienttype = 'Employee'
AND current = 2
UNION
SELECT md5
FROM other
WHERE @clienttype = 'Member'
AND current = 2;
Only one half of the UNION could be True, given the @clienttype predicate. 考虑到@clienttype谓词,只有一半的UNION可以为True。
Assuming SQL Server: 假设SQL Server:
You would need to use dynamic SQL. 您需要使用动态SQL。 Build the string and then call sp_executesql with the string. 构建字符串,然后使用字符串调用sp_executesql。
Edit: Better yet, just use if statements to execute the appropriate statement and assign the value to a variable. 编辑:更好的是,只需使用if语句来执行适当的语句并将值赋给变量。 You should avoid dynamic SQL if possible. 如果可能,您应该避免使用动态SQL。
No, you can't pick a table to query using a CASE statement. 不,您不能使用CASE语句选择要查询的表。 CASE statements only go within expressions, such as for a column's value or as part of your WHERE expression. CASE语句仅在表达式中,例如列的值或WHERE表达式的一部分。
This should do it, if you are looking for just one value: 如果您只查找一个值,这应该这样做:
IF @ClientType = 'Employee' BEGIN
SET @Source = (SELECT Md5 FROM HR WHERE Current = 2)
END
ELSE IF @ClientType = 'Member' BEGIN
SET @Source = (SELECT Md5 FROM Other WHERE Current = 2)
END
Since you don't specify what SQL backend you're going against, this will be hard to properly answer.... 既然你没有指定你要反对的SQL后端,那么很难正确回答....
As far as I can tell, you will not be able to do this neither against MS SQL Server, nor against Interbase/Firebird. 据我所知,您既不能对MS SQL Server也不能对Interbase / Firebird这样做。 I can't speak for other backend servers, though... 我不能代表其他后端服务器,但......
Marc 渣
I think it's pretty safe to say the answer is no way. 我认为答案是不可能的,这是非常安全的。 And that's regardless of SQL dialect. 而这与SQL方言无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.