2017-08-11 105 views
2

我在quotestable有如下记载:字符串操作

| quotesid | quotestags   | 
+----------+--------------------+ 
| 123  | Friendsip, Courage | 

我有以下查询:

update quotestable 
set quotestags = COALESCE(quotestags, '') + ', Friendship' 
where quotesid = 123 

update quotestable 
set quotestags = COALESCE(quotestags, '') +', Courtesy' 
where quotesid = 123 

在第一个查询我想追加Friendship标签在quotestag列中,但该值已经存在。我如何检查它的重复性?如果该值没有添加它。如果该值不存在,则添加它。

+3

这是糟糕的设计。单独存储每个引号 –

回答

3

试试这个

DEclare @Table TABLE(quotesid INT, quotestags VARCHAR(1000)) 
INSERT INTO @Table 
SELECT 123 ,'Friendship, Courage' UNION ALL 
SELECT 124 ,'Friendship, Courage' UNION ALL 
SELECT 125 ,'Relationship, Courage' UNION ALL 
SELECT 126 ,'Sincere Courage' 

--SELECT quotesid,quotestags,CHARINDEX('Friendship',quotestags) from @Table 

UPDATE t 
SET quotestags=COALESCE(o.quotestags, '') + ', Friendship' 
from @Table t 
INNER join @Table o 
ON o.quotesid=t.quotesid 
WHERE CHARINDEX('Friendship',t.quotestags)=0 

SELECT * from @Table 

结果

quotesid quotestags 
----------------------------------------------- 
123   Friendship, Courage 
124   Friendship, Courage 
125   Relationship, Courage, Friendship 
126   Sincere Courage, Friendship 
3

你可以尝试一些简单的像下面

update quotestable 
set quotestags = COALESCE(quotestags, '') + ', Friendship' 
where quotesid = 123 and NOT quotestags like '%Friendship%' 

update quotestable 
set quotestags = COALESCE(quotestags, '') +', Courtesy' 
where quotesid = 123 and NOT quotestags like '%Courtesy%'