Update and append unless empty

2019-08-21 14:50发布

Im trying to update a field by appending data to it. if it contains the data already i wont update it otherwise I will.

if it already contains data i want it to append a comma and space followed by the word. e.g.

update myTable 
set  Prefixes = convert(nvarchar(max),Prefixes) + ', abc' 
where MyCol='xyz' and Prefixes not like '%abc%'

im trying to get this to work so that if the prefixes column is empty initially it only includes the word 'abc'

and not ', abc'

How can i do this?

2条回答
Lonely孤独者°
2楼-- · 2019-08-21 15:46

You need to check for null values of Prefixes before filtering as NOT LIKE in the WHERE clause as well. Sql-Demo

update myTable 
set  Prefixes = isnull(nullif(rtrim(Prefixes),'') + ', abc','abc')
where MyCol='xyz' and isnull(Prefixes,'') not like ', abc%'
查看更多
一夜七次
3楼-- · 2019-08-21 15:47

Sounds like you need a CASE:

update myTable 
set  Prefixes = 
           case 
               when Prefixes is null or Prefixes = ''
               then 'abc'
               else convert(nvarchar(max),Prefixes) + ', abc' 
            end
where MyCol='xyz' and (Prefixes not like '%abc%' or Prefixes is null)

See SQL Fiddle with Demo

查看更多
登录 后发表回答