繁体   English   中英

sql server 2008 case语句中where子句不起作用

[英]sql server 2008 case statement in where clause not working

我有3个表格, DocumentsSRevents

documents我将保存与SR和事件相关的所有文档。

我想在一页中显示所有文档。

所以我正在使用这个选择查询

Select * 
from documents d, SR s, Events e 
where d.relationid = ( case d.documenttype when 'SR' the s.SRId else 'e.eventid end) 

但它不起作用。

我的document表结构是这样的:

documentid int, 
documenttype nvarchar(50),
relationid int,
document image,
docdate date

谁能指出我的错误?

我想选择所有带有相关信息的文档。 表示其SR文档是否比SR详细信息更应显示“事件”。 目前只有两种类型的文档。

我应该为此选择查询什么?

您可以先使用LEFT JOIN

SELECT  d.*,
        COALESCE(s.Col1, e.Col1) AS Col1,
        COALESCE(s.Col2, e.Col2) AS Col2,
        COALESCE(s.Col3, e.Col3) AS Col3,
        COALESCE(s.Col4, e.Col4) AS Col4
FROM    documents d
        LEFT JOIN SR s
            ON d.relationID = d.SRID
        LEFT JOIN Events e
            ON d.relationID = e.eventID

其中Col1,...., Col4是要基于documenttype显示的每个表的列。

要进一步获得有关联接的知识,请访问以下链接:

假设可以在SREvents表上包含相同的ID,则上述查询的更安全的版本是使用CASE()

SELECT  d.*,
        CASE WHEN d.documenttype = 'SR' THEN s.Col1 ELSE e.Col1 END) AS Col1,
        CASE WHEN d.documenttype = 'SR' THEN s.Col2 ELSE e.Col2 END) AS Col2,
        CASE WHEN d.documenttype = 'SR' THEN s.Col3 ELSE e.Col3 END) AS Col3,
        CASE WHEN d.documenttype = 'SR' THEN s.Col4 ELSE e.Col4 END) AS Col4
FROM    documents d
        LEFT JOIN SR s
            ON d.relationID = d.SRID
        LEFT JOIN Events e
            ON d.relationID = e.eventID

这些东西

SELECT 
    CASE WHEN SR.DocumentType = 'SR' THEN s.SRid ELSE e.eventId END AS Id
FROM documents d
LEFT JOIN SR s
ON s.SRId = d.relationId
LEFT JOIN Events e
ON e.EventId = d.relationId

这应该工作。

Select * 
from documents d
    left join SR s on d.relationid = d.SRId
    left join Events e on d.relationid = e.eventid
where d.relationid = ( case when d.documenttype = 'SR' then s.SRId else e.eventid end)

您无需编写Where子句,因为您需要所有记录

下面的查询确定

Select DocumentID,
       DocumentType,
       RelationID,
       case when DocumentType = 'SR' then S.SRID else E.EventID end as Doc_DataID
From 
      Documents D
Left outer join SR S on D.RelationID = S.SRID
LEFT OUTER JOIN EVENTS E on E.EventiD = D.RelationID

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM