是否可以在 sql From 子句中使用 Case 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/646334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:25:15  来源:igfitidea点击:

Is it possible to use a Case statement in a sql From clause

sqlsql-serversql-server-2005

提问by Zambian

Is it possible to use a Case statement in a sql From clause using SQL 2005? For example, I'm trying something like:

是否可以在使用 SQL 2005 的 sql From 子句中使用 Case 语句?例如,我正在尝试类似的事情:

SELECT Md5 FROM 
CASE
    WHEN @ClientType = 'Employee' THEN @Source = 'HR'
    WHEN @ClientType = 'Member' THEN  @Source = 'Other'
END CASE 
WHERE Current = 2;

采纳答案by jhale

Assuming SQL Server:

假设 SQL Server:

You would need to use dynamic SQL. Build the string and then call sp_executesql with the string.

您将需要使用动态 SQL。构建字符串,然后使用该字符串调用 sp_executesql。

Edit: Better yet, just use if statements to execute the appropriate statement and assign the value to a variable. You should avoid dynamic SQL if possible.

编辑:更好的是,只需使用 if 语句来执行适当的语句并将值分配给变量。如果可能,您应该避免使用动态 SQL。

回答by yukondude

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。

回答by Kevin Conner

No, you can't pick a table to query using a CASE statement. CASE statements only go within expressions, such as for a column's value or as part of your WHERE expression.

不,您不能使用 CASE 语句选择要查询的表。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

回答by marc_s

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. I can't speak for other backend servers, though...

据我所知,无论是针对 MS SQL Server 还是针对 Interbase/Firebird,您都无法做到这一点。不过,我不能代表其他后端服务器...

Marc

马克

回答by Tor Haugen

I think it's pretty safe to say the answer is no way. And that's regardless of SQL dialect.

我认为可以肯定地说答案是不可能的。这与 SQL 方言无关。