简体   繁体   中英

Update query with ISNULL in SQL SERVER

DateTime Should update if the data is passed else update it with original value which is already saved. This update does not works

DECLARE @FolderStatusDate DATETIME = NULL

SET @FolderStatusDate = '2012-07-04 14:09:04.043'

UPDATE CM.PfmFolder     
  SET   
      FolderStatusDate = ISNULL(@FolderStatusDate, FolderStatusDate)
      WHERE Id = @Id  

Why don't you move the check for NULL to the WHERE clause?

DECLARE @FolderStatusDate DATETIME = NULL

SET @FolderStatusDate = '2012-07-04 14:09:04.043'

UPDATE CM.PfmFolder     
  SET   
      FolderStatusDate = @FolderStatusDate
      WHERE Id = @Id  
      AND @FolderStatusDate IS NOT NULL

You can also do it this way

DECLARE @FolderStatusDate DATETIME = NULL

SET @FolderStatusDate = '2012-07-04 14:09:04.043'

UPDATE CM.PfmFolder     
SET   
  FolderStatusDate = case when ISNULL(@FolderStatusDate, '') = '' 
                           then FolderStatusDate else @FolderStatusDate end
  WHERE Id = @Id

A slight edit on Hitesh Salian's answer

 DECLARE @FolderStatusDate DATETIME = NULL

 SET @FolderStatusDate = '2012-07-04 14:09:04.043'

 UPDATE CM.PfmFolder     
 SET   
 FolderStatusDate = case @FolderStatusDate is Null
                       then FolderStatusDate else @FolderStatusDate end
 WHERE Id = @Id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM