简体   繁体   中英

How can I conditionally update a text/ntext field in SQL?

In a stored procedure I'm trying to conditionally update a field (like the 2nd line in the SQL statement below)

UPDATE [some_stuff] SET
  last_update = CASE WHEN val = @NewVal THEN last_update ELSE GETDATE() END,
  val = @NewVal

...but for a text/ntext field. What's the most efficient way to go about doing that? Does it have to be a separate UPDATETEXT statement? And do I have to do an extra SELECT first?

The above example will work in SQL Server 2005 where val is a Text field and you're updating the whole value. If you're only replacing part of a field then use UPDATETEXT in a separate statement.

A better solution, if you can update the schema is to use VARCHAR(MAX) or NVARCHAR(MAX) columns. The UPDATETEXT command has been marked as deprecated in a future release of SQL Server. If you're using these data types then you can use the column_name.WRITE in the UPDATE statement to replace part of a value.

Maybe the example isn't realistic, but couldn't you simplify this down to:

UPDATE [some_stuff] 
SET last_update =  GETDATE()
WHERE val != @NewVal

The first half of the case just sets the field to itself, which seems kinda pointless.

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