-1

我需要一个查询来更新用户表。我在下面写了一个,它工作正常。但我需要根据 Proc 发送的参数更新特定属性,有人有什么好主意吗?

--table
 users(userID,firstname,lastName,age,UserTypeID,classID,SectionID)
 --SP

'CREATE Proc UpdateUsers
   (
   @pUserID int ,
   @pFirstName varchar(50),
   @pLastName varchar(50), 
   @pAge int,
   @pUserTypeID int,
   @pClassID int,
   @pSectionID int
  )
   as
    if not exists (select 'true' from Users where UserID=@pUserID)
    begin
print ('operation cannot complete; No such User founded, please enter valid UserID')
return
    end

   if exists (select 'true' from UserTypes where UserTypeID=@pUserTypeID)
   begin
if exists (select 'true' from SectionsClasses where ClassID=@pClassID and 
                         SectionID=@pSectionID)
    update users set FirstName=@pFirstName,  
                             LastName=@pLastName,
                             Age=@pAge, 
                             UserTypeID=@pUserTypeID, 
                             ClassID=@pClassID,
                             SectionID=@pSectionID 

            where UserID=@pUserID
        else
    print ('operation cannot complete; No such Class OR Section founded, please enter valid ClassID AND  DectionID')
end
else
print ('operation cannot complete; No such UserType founded')

GO'
4

1 回答 1

1

您可以使用COALESCEwhich 返回其第一个非 NULL 表达式,以允许您传递NULL您不想更新的任何值。你SET看起来像:

set FirstName=COALESCE(@pFirstName,FirstName),  
    LastName=COALESCE(@pLastName,LastName,
    Age=COALESCE(@pAge,Age), 
    UserTypeID=COALESCE(@pUserTypeID,UserTypeID), 
    ClassID=COALESCE(@pClassID,ClassID),
    SectionID=COALESCE(@pSectionID,SectionID)

如您所见,如果任何参数为NULL,我们只需将列设置为等于其自身。

于 2013-10-01T07:19:31.567 回答