如何在CASE中执行SELECT语句

时间:2019-01-08 06:15:30

标签: sql sql-server

我有两个SELECT查询。

SELECT FullName FROM TableA
SELECT FirstName FROM  TableB

我想在CASE中执行两条语句,或者是否有其他选择。

如果SELECT FullName FROM TableA返回NULL或根本没有任何行,则它应运行以下查询:

SELECT FirstName FROM TableB

我可以在这里使用两个CASE语句,但是每个表中大约有20列,这将使40 CASE语句最终使查询很长。

2 个答案:

答案 0 :(得分:2)

SELECT FullName FROM TableA
union 
SELECT FirstName FROM  TableB 
where not exists 
  (SELECT FullName FROM TableA)

Working Fiddle

答案 1 :(得分:1)

我认为这就是您要搜索的内容

IF EXISTS (SELECT 1 FROM TableA) 
    SELECT FullName AS Name, TableA.Field1 AS FinalField1, 
           TableA.Field2 AS FinalField2... 
    FROM TableA
ELSE
    SELECT FirstName AS Name, TableB.Field1 AS FinalField1, 
           TableB.Field2 AS FinalField2... 
    FROM TableB