[英]from existing value Update column using comma-separated values in SQL Server
from existing value Update column using comma-separated values in SQL Server 从现有值更新列中使用逗号分隔的值在SQL Server中
tbl
id name rev_code
1 aaa rev1,rev2,rev3
2 bbb rev2,rev3
3 ccc rev1,rev2
4 ddd rev3,rev2
i want update where rev_code='rev3' need to add end of with , like rev1,rev2,rev3,rev5 我想更新rev_code ='rev3'需要添加的结尾,如rev1,rev2,rev3,rev5
expecting output 期望的输出
id name rev_code
1 aaa rev1,rev2,rev3,rev5
2 bbb rev2,rev3,rev5
3 ccc rev1,rev2
4 ddd rev3,rev2,rev5
Your best option would be to normalize your database: 最好的选择是规范化数据库:
Get rid of that rev_code
column and turn it into a new table, linked with a foreign key constraint to the current table. 删除该rev_code
列,然后将其转换为新表,并通过外键约束将其链接到当前表。
If that's impossible, you can do something like this: 如果不可能,则可以执行以下操作:
UPDATE tbl
SET rev_code = rev_code + ',rev5'
WHERE ','+ rev_code + ',' LIKE '%,rev3,%'
AND ','+ rev_code + ',' NOT LIKE '%,rev5,%'
Stop storing comma separated values in a column it violates First Normal form . 停止将逗号分隔的值存储在违反“ 第一范式”形式的列中。 Consider changing your database design 考虑更改数据库设计
At worst case use this update to get the result 在最坏的情况下,请使用此更新获取结果
UPDATE Yourtable
SET [rev_code] = [rev_code] + ',rev5'
WHERE Charindex('rev3', [rev_code]) > 0
Try this, 尝试这个,
UPDATE table1 SET rev_code=rev_code +',rev5'
where rev_code like '%rev3%' and Charindex('rev5', [rev_code])= 0
edited: 编辑:
UPDATE table1 SET rev_code= rev_code +',rev5'
where rev_code IS NOT NULL and rev_code like '%rev3%' and Charindex('rev5', [rev_code])= 0
Check rev_code column size. 检查rev_code列大小。
And as @Zohar Peled said, it is a bad idea while storing comma separated values. 正如@Zohar Peled所说,在存储用逗号分隔的值时,这是一个坏主意。
Is storing a delimited list in a database column really that bad? 将分隔列表存储在数据库列中真的不好吗?
Try this, this will rev5
for the rev_code if there is rev3
and rev5
already not exists. 试试这个,这将rev5
为rev_code如果有rev3
和rev5
已经不存在。
UPDATE tbl
SET rev_code = rev_code + ',rev5'
WHERE rev_code NOT LIKE '%rev5%' AND rev_code LIKE '%rev3%'
Ouch...you have your db design wrong so i will first suggest to create additional one-to-many table where you would store fields: originalTableRecordId | 糟糕...您的数据库设计有误,因此我将首先建议创建一个额外的一对多表,您将在其中存储字段: rev_code rev_code
then you find all records in that table that have particular rev_code value and add new one to those that meet criteria. 然后在该表中找到所有具有特定rev_code值的记录,并将新记录添加到满足条件的记录中。
If you cant change your db structure then you have to go with either "WHERE rev_code like '%rev3%' " (which will be awfully slow) or with fulltext search (which is a huge overkill) 如果您不能更改数据库结构,则必须使用“ WHERE rev_code like'%rev3%'”(这将非常慢)或全文搜索(这是一个过大的杀伤力)
how about: 怎么样:
UPDATE table
SET rev_code = rev_code+',rev5'
WHERE rev_code LIKE '%rev3%' (OR RIGHT(rev_code,4) = 'rev3')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.