开发者

Question about SQL UPDATE with CASE statement

So I have this SQL table that I need to update. Now we use a tool to do the process so if we just renamed the column then it wouldn't work because our tool would just drop t开发者_如何学Pythonhe old column and add a new column with the new name, so we have to do it manually and enter this code into the build and exclude the table from our build.

The table we CURRENTLY have has a column called 'FeeTypeId'. We have another table, a Lookup table, that has a bunch of ID's relating to types and descriptions. We want that previous 'FeeTypeId' field on the other table I just mentioned, to contain these LookupId's which relate to their specific 'FeeDescription's. I will have an Excel sheet that contains the mappings, so for right now there is no real data, just logic.

Here is the script I wrote but I don't know if it will run. Can you guys help me out?

----------------------------------------------------------------------
--PRE_UPGRADE--
----------------------------------------------------------------------

CREATE TABLE dbo.TmpFeesToRules(OldValue varchar, NewValue varchar)
--populate with values from Excel

----------------------------------------------------------------------
--POST UPGRADE--
----------------------------------------------------------------------

UPDATE Lending.ApplicationFee
    SET FeeTypeId = 
        CASE t.NewValue 
            WHEN <> null THEN (SELECT LookupID FROM tblLookup WHERE LookupType = 'FEE_CODE' AND LookupDesc = t.NewValue)
            ELSE (SELECT LookupID FROM tblLookup WHERE LookupType = 'FEE_CODE' AND LookupCode = 'OTHER') END
            -- else might change, might not even need an else

    FROM TmpFeesToRules t INNER JOIN tblLookup l ON t.NewValue = l.LookupDesc

    -- Drop the tmp table
    DROP TABLE dbo.TmpFeesToRules


I can't really test this but the following is, according to Toad, valid SQL. Perhaps you can try to run this:

UPDATE Lending.ApplicationFee
SET FeeTypeId = 
(
    CASE WHEN t.NewValue  IS NOT NULL THEN 
        (SELECT LookupID FROM tblLookup WHERE LookupType = 'FEE_CODE' AND LookupDesc = t.NewValue)
    ELSE 
        (SELECT LookupID FROM tblLookup WHERE LookupType = 'FEE_CODE' AND LookupCode = 'OTHER')
    END
)
FROM TmpFeesToRules t 
INNER JOIN tblLookup l ON t.NewValue = l.LookupDesc
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜