select语句中的条件逻辑

时间:2016-02-24 14:43:34

标签: sql-server sql-server-2008 sql-server-2012 sql-server-2008-r2

我有以下查询工作得很好但我遇到了一些我以前没见过的记录。它们不是<InstrumentID>而是<OriginalInstrumentID>。我希望我的查询能够同时获取。因此,如果找不到<InstrumentID>,请检查并返回<OriginalInstrumentID>,否则NULL

<OriginalInstrumentID>仅在msg_typeACCTV21时显示。我不确定我是否应该使用case语句,IF..Then..ELSE,布尔逻辑..或其他任何东西。我一直在读这么多,我完全被解散了。救命。请。

Use Database
DECLARE @First VARCHAR(15), @Second VARCHAR(15)
SET @First = '<InstrumentID>'
SET @Second = '</InstrumentID>'

select *
from 
(
        SELECT out_interface_id, msg_id , 
        SUBSTRING(xml_msg, CHARINDEX(@First, xml_msg) + LEN(@First), 
                 CHARINDEX(@Second, xml_msg) - 
                 CHARINDEX(@First, xml_msg) - 
                 LEN(@First)) as InstrumentID,
        msg_type, xml_msg, CAST(xml_msg AS XML) as [Quick_XML], 
        date_received,status, last_modified, environment,
        transaction_closed_date
        from Table1 
        where msg_type in ('BALMIS','ACCTV21') 
        and date_received >= CAST(GETDATE() -1 as DATE)
        and date_received < CAST(GETDATE() as DATE)
) x
where x.InstrumentID = 'ABC123'
order by date_received desc 

1 个答案:

答案 0 :(得分:2)

我会在CASE中找到SELECT声明,例如

InstrumentID=
    CASE WHEN CHARINDEX(@First,xml_msg)<>0 -- found <InstrumentId>?
    THEN SUBSTRING(xml_msg, CHARINDEX(@First, xml_msg) + LEN(@First),  -- lookup <InstrumentId>
                 CHARINDEX(@Second, xml_msg) - 
                 CHARINDEX(@First, xml_msg) - 
                 LEN(@First))
    ELSE CASE WHEN msg_type='ACCTV21' AND CHARINDEX('<OriginalInstrumentId>',xml_msg)<>0 -- found <OriginalInstrumentId>?
         THEN -- lookup <OriginalInstrumentId>
         ELSE NULL -- not found any instrument element
         END
    END