我可以使用Case语句来决定要更新哪个表吗?

时间:2014-07-25 11:37:43

标签: sql sql-server

我正在尝试编写一些SQl,它将根据传入的参数值选择要更新的表

以下是可能的吗?

UPDATE    CASE @param
            WHEN '02' THEN dbo.Employer
            WHEN '03' THEN dbo.Group
            WHEN '04' THEN dbo.Sub_Group
            WHEN '05' THEN dbo.Member
            WHEN '07' THEN dbo.Claim
            WHEN '08' THEN dbo.Contact
        END
        SET Status_PKID = 4
        WHERE Request_PKID = 1

我已尝试过这方面的内容,但我在case语句中遇到了语法错误。我想知道这是否只是我正确编写SQL的问题,还是我必须以一种非常不同的方式重写这一切(可能使用IF语句和每个表的单独UPDATE)

4 个答案:

答案 0 :(得分:4)

是的,您需要IF语句

IF @param = '02'
UPDATE dbo.Employer
SET Status_PKID = 4
WHERE Request_PKID = 1

IF @param = '03'
UPDATE dbo.Group
SET Status_PKID = 4
WHERE Request_PKID = 1

IF @param = '04'
UPDATE dbo.Sub_Group
SET Status_PKID = 4
WHERE Request_PKID = 1

IF @param = '05'
UPDATE dbo.Member
SET Status_PKID = 4
WHERE Request_PKID = 1

IF @param = '07'
UPDATE dbo.Claim
SET Status_PKID = 4
WHERE Request_PKID = 1

IF @param = '08'
UPDATE dbo.Contact
SET Status_PKID = 4
WHERE Request_PKID = 1

答案 1 :(得分:2)

不,你做不到。

您可以使用动态SQL来实现类似的功能。

declare @sql nvarchar(1000)

select @sql = 'UPDATE ' +   CASE @param
            WHEN '02' THEN 'dbo.Employer'
            WHEN '03' THEN 'dbo.Group'
            ...
        END + ' SET Status_PKID = 4 WHERE Request_PKID = 1'

但这可能是一个坏主意

答案 2 :(得分:2)

使用动态查询

SET @table = (CASE @param
            WHEN '02' THEN 'dbo.Employer'
            WHEN '03' THEN 'dbo.Group'
            WHEN '04' THEN 'dbo.Sub_Group'
            WHEN '05' THEN 'dbo.Member'
            WHEN '07' THEN 'dbo.Claim'
            WHEN '08' THEN 'dbo.Contact' END)

SET @SQL = 'UPDATE  ' + @Table + ' SET Status_PKID = 4 WHERE Request_PKID = 1'

EXEC (@SQL)

答案 3 :(得分:2)

DECLARE @SQL NVARCHAR(MAX);

SET @SQL =  N'UPDATE  [dbo].'  +  CASE @param
                                     WHEN '02' THEN QUOTENAME(Employer)
                                     WHEN '03' THEN QUOTENAME(Group)
                                     WHEN '04' THEN QUOTENAME(Sub_Group)
                                     WHEN '05' THEN QUOTENAME(Member)
                                     WHEN '07' THEN QUOTENAME(Claim)
                                     WHEN '08' THEN QUOTENAME(Contact)
                                  END
        +  N'  SET Status_PKID = 4
           WHERE Request_PKID = 1 '

EXECUTE sp_executesql @SQL