简体   繁体   中英

sql server 2008 case statement in where clause not working

I have 3 table, Documents , SR and events

In documents I am saving all documents related to SR and Events.

And I want to show all documents in one page.

So I am using this select query

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

but it's not working.

My document table structure is like this :

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

Can anyone please point me to my mistake ?

I want to select all documents with related info. means if its SR document than SR details should display otherwise Events. There is only 2 types of documents right now.

What should be my select query for this ?

You can join then using 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

where Col1,...., Col4 are the columns of each table youw ant to be displayed based on documenttype .

To further gain more knowledge about joins, kindly visit the link below:

The more safe version of the query above assuming that the same ID can contain on SR and Events table would be by using 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

Something along these lines

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

This should work.

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)

You no need to write Where clause as you need all records

Below Query Works for sure

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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