SQL-根据列值使用不同的Select语句

时间:2018-07-31 12:54:23

标签: sql

例如,

Select field1

From table1

when table1.field1 = 'S'

     then (select field1,2,3,4,5,6,.....
           form table1,2,3,4,5,6,....(with joins))

when table1.field1 = 'O'

     then (select field1,2,3,4,5,6,.....
           from table1,2,3,4,5,6,.....(with join))

2 个答案:

答案 0 :(得分:0)

我想我满足了您的需求。一种可能的解决方案是创建一个带有硬编码where子句的视图。这是主意:

CREATE VIEW ConditionalSelect AS
SELECT ...fields...
FROM ...tables...
JOIN ...joins...
WHERE table1.field1 = 'S'
AND ....

UNION

SELECT ...fields...
FROM ...tables...
JOIN ...joins...
WHERE table1.field1 = 'O'
AND ....

然后您可以执行以下操作:

SELECT * 
FROM ConditionalSelect
WHERE field1 = 'S'

注意:两个SELECT必须具有相同的列,列类型和列名,否则VIEW不会编译。

答案 1 :(得分:0)

您可以这样做:

DECLARE @Field1 VARCHAR(10) =
(
    SELECT Field1
    FROM table1
);

IF(@Field1 = 'S')
BEGIN
    SELECT *
    FROM table1 t1
        INNER JOIN table2 t2
            ON t2.col1 = t1.col1 
END
ELSE IF (@Field1 = 'O')
BEGIN
    SELECT *
    FROM table1 t1
        INNER JOIN table2 t2
            ON t2.col1 = t1.col1 
END

使您免于创建视图