将删除语句添加到if语句

时间:2019-05-03 13:28:04

标签: sql sql-server

我正在尝试将delete语句添加到现有的IF语句中。

我尝试在语句的开头和结尾添加语句,但是它不起作用。

这是我为update和insert语句创建的现有代码。

IF EXISTS (SELECT * FROM [int_SocialAccess].[dbo].[Authorisers] where ID = {ID})
update [int_SocialAccess].[dbo].[Authorisers] set 
        Name = {Name},
        Email = {Email},
        Responsibility = {Responsibility},
        IsHeadOfService = {IsHeadOfService},
        DeleteRec = {DeleteRec}
    where ID = {ID}
ELSE
    insert into [int_SocialAccess].[dbo].[Authorisers] 
    values( {Name},
        {Email},
        {Responsibility},
        {IsHeadOfService},
        'no')

如果“ DeleteRec”字段为“是”,我想在更新语句之前的下面添加删除语句。

IF {DeleteRec} = 'yes'
    DELETE FROM [int_SocialAccess].[dbo].[Authorisers]
    where ID = {ID}
ELSE

任何迹象都很好。

1 个答案:

答案 0 :(得分:4)

如果在if-else块中需要多个stmt,则需要以BEGIN END包装-

IF EXISTS (SELECT * FROM [int_SocialAccess].[dbo].[Authorisers] where ID = {ID})
BEGIN
    IF {DeleteRec} = 'yes'
        DELETE FROM [int_SocialAccess].[dbo].[Authorisers] where ID = {ID}
    ELSE
         Update
END
ELSE
    insert into [int_SocialAccess].[dbo].[Authorisers] 
    values( {Name},
        {Email},
        {Responsibility},
        {IsHeadOfService},
        'no')