使用case或if else条件存储过程以获取更新记录

时间:2014-02-24 09:43:43

标签: sql-server tsql stored-procedures

我有桌子我想根据用户ID写sp更新我写的条件我想要使用,否则或sp中的情况条件...我将如何写?

table:    
    SELECT [ConId], [User_Id], [UserName], [UserStatus], [ContUser_Id], 
    [ContUserName], [ContUserStatus], [ContBlock], [ContDelete], [Active], [Date] 
    FROM   [dbo].[bb_Contact] 

sp:

    CREATE PROC [dbo].[bb_UpdateContactId] 
    @ContId int, @UserId int
    AS 
    SET NOCOUNT ON 
    SET XACT_ABORT ON  

    BEGIN TRAN  

    if(@UserId = [User_Id])
    {
        update [bb_Contact]
        set [UserStatus]=1,
        where [ConId]= @ContId
    }
    else if(@UserId=[ContUser_Id])
    {
        update [bb_Contact]
        set [ContUser_Id]=1
        where [ConId]= @ContId
    }

    COMMIT
GO

1 个答案:

答案 0 :(得分:1)

试试这个:

CREATE PROC [dbo].[bb_UpdateContactId] 
@ContId int, @UserId int
AS 
SET NOCOUNT ON 
SET XACT_ABORT ON  

BEGIN TRAN  

if exists
(select * 
 from [bb_Contact] 
 where [ConId]= @ContId 
       and @UserId = [User_Id])
    update [bb_Contact]
    set [UserStatus]=1
    where [ConId]= @ContId
    and @UserId = [User_Id]
else
    update [bb_Contact]
    set [ContUser_Id]=1
    where [ConId]= @ContId
    and @UserId=[ContUser_Id]

COMMIT