2013-10-01 26 views
-1

我需要一個查詢來更新用戶表。我寫下了一個,它工作正常。 但我需要根據Proc發送的參數更新特定屬性,任何人都有任何好主意?更新行sql服務器中的特定屬性

--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 [email protected]) 
    begin 
print ('operation cannot complete; No such User founded, please enter valid UserID') 
return 
    end 

    if exists (select 'true' from UserTypes where [email protected]) 
    begin 
if exists (select 'true' from SectionsClasses where [email protected] and 
         [email protected]) 
    update users set [email protected], 
          [email protected], 
          [email protected], 
          [email protected], 
          [email protected], 
          [email protected] 

      where [email protected] 
     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' 
+2

您只需添加額外的參數並使用IF子句處理它們。 – athabaska

+0

這將增加許多額外的代碼:3 – abodvdv

+1

@abodvdv沒有更簡單,更直接的方式來做到這一點。你是固執的還是什麼? ''太多額外的代碼''? –

回答

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,我們只需設置列等於本身。

+0

到很多額外的代碼 – athabaska

+0

@athabaska - 你的建議可能被OP解釋爲「對每個可能的組合做一個if併爲每個組合編寫一個單獨的UPDATE語句」 - 這對於任何合理數量的參數。 –