0

I have this scenario ---- where a stored procedure may be given parameter values optionally. If the values are empty/default I would like to retain the existing values.

Is the following way of handling it with CASE statements correct? This works for me but is there a better way to do this?

CREATE  PROCEDURE [UpdateUser]        
(      
 @UserID int, 
 @UserKey VARCHAR(32),     
 @UserName varchar(50),      
 @CategoryID INT = 0,  

)        
AS        
BEGIN      

 SET NOCOUNT ON      

 UPDATE [Users]      
 SET 
   [UserKey] =  (CASE WHEN (LEN(RTRIM(LTRIM(@UserKey)))>0) THEN @UserKey ELSE UserKey END )  
  ,[UserName] = (CASE WHEN (LEN(RTRIM(LTRIM(@UserName)))>0) THEN @UserName ELSE UserName END )       
  ,[CategoryID] = (CASE WHEN (@CategoryID>0) THEN @CategoryID ELSE CategoryID END )    

 WHERE         
  [UserID] = @UserID      

END
4

1 回答 1

1

一种“更好”(就语法简单性而言)的方法是使用NULLIF()and ISNULL/COALESCE而不是 CASE 表达式:

UPDATE [Users]      
SET 
  UserKey    = COALESCE(NULLIF(@UserKey   , ''), UserKey   ),
  UserName   = COALESCE(NULLIF(@UserName  , ''), UserName  ),
  CategoryID = COALESCE(NULLIF(@CategoryID, 0 ), CategoryID)    
WHERE         
  UserID = @UserID
;

为了解释 and 的缺失,LTRIM()RTRIM()Transact-SQL 中的字符串比较中将忽略尾随空格。这意味着一个(任意数量的)空格字符串将匹配另一个(任何其他数量的)空格字符串,以及一个空字符串。(而且,就此而言,该LEN()函数在计算字符串的长度时也会忽略尾随空格,因此,例如,LEN(SPACE(10))将返回 0 而不是 10。)

于 2013-08-13T11:47:26.987 回答