Corrsor中复杂CASE语句的正确语法

时间:2011-10-12 21:16:03

标签: sql cursor case sql-update

我需要帮助我的Cursor中的CASE语句使用正确的语法。

背景:我想要这个CASE语句要做的是查看表Concatenated_File和列FileID中任何一行显示'File1',我希望它更新相应表中的MRNID,标题为Load_File_1 。我想继续CASE语句,即任何一行显示'File2',我希望它更新相应表中的MRNID,Load_File_2。

这是我到目前为止所做的,但我无法弄清楚正确的语法。任何帮助,将不胜感激。感谢。

DECLARE @FILEID AS VARCHAR(255)
DECLARE @MRNID AS VARCHAR(255)
DECLARE @UniqueID AS VARCHAR(255)
DECLARE @LNAME AS VARCHAR(255)
DECLARE @FNAME AS VARCHAR(255)
DECLARE @Birthdate AS VARCHAR(255)
DECLARE @SSN AS VARCHAR(255)
DECLARE @HOLD_MRNID AS VARCHAR(255)
DECLARE @HOLD_UniqueID AS VARCHAR(255)
DECLARE @HOLD_LNAME AS VARCHAR(255)
DECLARE @HOLD_FNAME AS VARCHAR(255)
DECLARE @HOLD_Birthdate AS VARCHAR(255)
DECLARE @HOLD_SSN AS VARCHAR(255)

SET NOCOUNT ON
DECLARE curDB CURSOR FAST_FORWARD FOR

-----------------------------------------------
SELECT UniqueID, MRNID, LNAME, FNAME, Birthdate, SSN
FROM Concatenated_File
ORDER BY LNAME, FNAME, Birthdate, SSN
-----------------------------------------------

-- initialize variables
select @FILEID=''
select @MRNID=''
select @UniqueID=''
select @FNAME=''
select @LNAME=''
select @Birthdate=''
select @SSN=''
select @HOLD_MRNID=''
select @HOLD_UniqueID=''
select @HOLD_FNAME=''
select @HOLD_LNAME=''
select @HOLD_Birthdate=''
select @HOLD_SSN=''

OPEN curDB

FETCH NEXT FROM curDB into @FILEID, @MRNID, @UniqueID, @FNAME, @LNAME, @Birthdate, @SSN
WHILE (@@FETCH_STATUS = 0)
  BEGIN

        IF @LNAME = @HOLD_LNAME and @FNAME = @HOLD_FNAME and @Birthdate = @HOLD_Birthdate and @SSN = @HOLD_SSN
              BEGIN

                    select @FILEID
                        CASE
                            When @FILEID = 'File1' Then
                            Update Load_File1
                            Set MRNID = @HOLD_MRNID
                            Where UniqueID = @UniqueID

                            When @FILEID = 'File2' Then
                            Update Load_File2
                            Set MRNID = @HOLD_MRNID
                            Where UniqueID = @UniqueID



              END
        ELSE

              BEGIN
                    select @HOLD_UniqueID = @UniqueID
                    select @HOLD_MRNID = @MRNID
                    select @HOLD_FNAME = @FNAME
                    select @HOLD_LNAME = @LNAME
                    select @HOLD_Birthdate = @Birthdate
                    select @HOLD_SSN = @SSN
              END
        FETCH NEXT FROM curDB into @FILEID, @MRNID, @UniqueID, @FNAME, @LNAME, @Birthdate, @SSN
  END

关闭curDB DEALLOCATE curDB

1 个答案:

答案 0 :(得分:1)

CASE不是您需要的控制流程IF

IF @FILEID = 'File1'
    UPDATE Load_File1
    SET MRNID = @HOLD_MRNID
    WHERE UniqueID = @UniqueID
ELSE IF @FILEID = 'File2'
    UPDATE Load_File2
    SET MRNID = @HOLD_MRNID
    WHERE UniqueID = @UniqueID

我不确定你的游标更新逻辑究竟在做什么。通常,您最好使用基于集合的技术。