我需要一个查询来更新用户表。我写了下面的一个,它工作正常。 但我需要根据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'
答案 0 :(得分:1)
您可以使用COALESCE
返回其第一个非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
,我们只需将列设置为等于它自己。