SQL 根据sql中的case语句创建select语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3102600/
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 06:39:18  来源:igfitidea点击:

create select statement based on case statement in sql

sql

提问by Ben

Is there a clean way in sql to create a select statement based on a case statement?

sql中是否有一种干净的方法可以根据case语句创建select语句?

I'm looking for the basic logic to be something like

我正在寻找类似的基本逻辑

   CASE @tableToUse
           WHEN 'Table1' SELECT * FROM Table1 
           WHEN 'Table2' SELECT * FROM table2 
           DEFAULT 'Table3' SELECT * FROM table3
   END CASE

回答by TLiebe

In T-Sql (MS SQL Server) you can dynamically compose your SQL statement and then use the sp_executesqlmethod to execute it. Based on your case statement you can build a SELECT statement using a variable and then use sp_executesql to run it. The one thing to be aware of is that you need to make sure you clean any input you get from users if you are using text directly from users to prevent SQL injection attacks.

在 T-Sql (MS SQL Server) 中,您可以动态地编写 SQL 语句,然后使用sp_executesql方法执行它。根据您的 case 语句,您可以使用变量构建 SELECT 语句,然后使用 sp_executesql 运行它。需要注意的一件事是,如果您直接使用来自用户的文本来防止 SQL 注入攻击,则需要确保清除从用户那里获得的任何输入。

For example,

例如,

DECLARE @sql NVARCHAR(200)

SELECT @sql = CASE @tableToUse
    WHEN 'Table1' THEN 'SELECT * FROM Table1'
    WHEN 'Table2' THEN 'SELECT * FROM Table2'
    ELSE 'Table3' THEN 'SELECT * FROM Table2'
    END

EXECUTE sp_executesql @sql

You should be able to do something similar in other versions of SQL.

您应该能够在其他版本的 SQL 中执行类似的操作。

回答by JohnFx

Sorry, Case statements in tSQL (which I assume you are asking about) are for evaluating expressions only and can't be used for control flow.

抱歉,tSQL 中的 Case 语句(我假设您正在询问)仅用于评估表达式,不能用于控制流。

You are pretty much stuck with IF..THEN

你几乎被 IF..THEN 困住了

IF (@Something='Table1')
    SELECT Field1 from table1
ELSE
   IF (@Something='Table2')
        SELECT Field1 from table2
   ELSE
        SELECT Field1 From table3

回答by Astro

Well, this is old, but in case it is helpful:

嗯,这是旧的,但如果它有帮助:

CASE WHEN <Variabe> THEN (SELECT <Column> FROM <Table>) END

回答by Baaju

You can do this ! only that you cannot do a "select *" as that might return more than one value that shoot an error even if that has to be a table with a single column

你可以这样做 !只是您不能执行“选择 *”,因为它可能会返回多个会引发错误的值,即使它必须是具有单列的表

SELECT   columnName = CASE WHEN 'foo' THEN select <Column_Name> from tableName where columnName = 'this'  
                           WHEN 'bar' THEN select <Column_Name>  from tableName where columnName = 'that' 
END 
FROM tableName 

回答by HLGEM

Why not just join to the testTable on username?

为什么不直接加入用户名的 testTable?