案例条件加入列

时间:2016-04-08 18:45:04

标签: tsql join conditional case

第15行,第1行,第8行 关键字' CASE'

附近的语法不正确

我正在尝试根据列值加入列。

如果情况条件1为真,那么我想加入 ON im.ItemNumber = left(tr.itemnumber,len(tr.itemnumber)-4)

如果案例条件2为真,那么

ON tr.ItemNumber = im.LegacyItemNumber

否则

tr.ItemNumber = im.ItemNumber

    SELECT 
           im.Category as RootCategory,GETDATE() AS LoadDate,tr.*  
          into transactionreport_stage_testNN
    FROM transaction tr
    LEFT OUTER JOIN ALLDW_ora.dbo.Location(NOLOCK) loc ON tr.location=loc.location

    CASE 
    when
    right(tr.itemnumber,4) = '_old' then 
    LEFT OUTER JOIN [Inventory](NOLOCK) im
    ON im.ItemNumber = left(tr.itemnumber,len(tr.itemnumber)-4)


    when 
    tr.itemnumber <> im.ItemNumber 
    then
    LEFT OUTER JOIN [Inventory](NOLOCK) im
    ON tr.ItemNumber = im.LegacyItemNumber

else
LEFT OUTER JOIN [Inventory](NOLOCK) im
ON tr.ItemNumber = im.itemnumber

    end 

    AND im.Location=loc.LocationNo

Schema

1 个答案:

答案 0 :(得分:0)

你应该只使用AND和OR的

LEFT OUTER JOIN [Inventory](NOLOCK) im ON im.Location=loc.LocationNo 
        AND (
            (right(tr.itemnumber,4) = '_old' AND im.ItemNumber = left(tr.itemnumber,len(tr.itemnumber)-4))
            OR 
            (tr.itemnumber <> im.ItemNumber AND tr.ItemNumber = im.LegacyItemNumber)
            OR
            (tr.ItemNumber = im.itemnumber)          
        )

它可能就像

一样简单
SELECT  im.Category AS RootCategory,
        GETDATE() AS LoadDate,
        tr.*
INTO    #transactionreport_stage_testNN
FROM    [transaction] tr
        LEFT OUTER JOIN ALLDW_ora.dbo.Location (NOLOCK) loc ON tr.location = loc.location
        LEFT OUTER JOIN [Inventory] (NOLOCK) im ON im.Location = loc.LocationNo
            AND REPLACE(tr.itemnumber, '_old', '') IN (im.itemnumber, im.legacyitemnumber)