如果存在,则从多个表中选择值

时间:2016-03-16 18:32:43

标签: sql sql-server tsql sql-server-2012

我正在使用三张桌子。

Table A = Training_Requests (title varchar(20), intID INT)

Table B = Content_Requests (title varchar(20), intID INT)

Table C = Projects (intID INT, otherField varchar(20))

我正在尝试撰写SELECT语句,我可以传递intID,并告诉我是否有Training_Request和/或Content_Request.

我正在寻找一个可能是ContentTrainingContent and Training

的结果集

示例:

DECLARE @intID INT = '123

SELECT 'Training' as val,
       (SELECT 'Content' as val
        FROM Content_Requests as cr
        WHERE cr.intID = @intID)
FROM Training_Requests as tr 
WHERE tr.intID = @intID

上面会返回两列不是我想要的结果。

如果Content_Request和Training_Request都存在,则应该返回两个单独的记录。

结果应如下所示,假设Training_Request和Content_Request都存在:

enter image description here

我无法创建临时表,因为它将位于视图中。

更新

使用Giorgos Betsos的回答,我收到以下错误: Subquery returned more than 1 value.

enter image description here

2 个答案:

答案 0 :(得分:4)

使用UNION

SELECT 'Training' as val
FROM Training_Requests as tr 
WHERE tr.intID = @intID

UNION

SELECT 'Content' as val
FROM Content_Requests as cr
WHERE cr.intID = @intID

答案 1 :(得分:1)

DECLARE @intID int = 123;
SELECT CASE WHEN cr.intID IS NOT NULL AND tr.intID IS NOT NULL THEN 'Content and Training'
            WHEN cr.intID IS NOT NULL THEN 'Content'
            WHEN tr.intID IS NOT NULL THEN 'Training'
       END
FROM Training_Requests tr
FULL OUTER JOIN Content_Requests  cr
    ON tr.intID = cr.intID 
WHERE cr.intID = @intID OR tr.intID = @intID