How to remove duplicates within a string from the table in SQL server 2016(如何在SQL Server 2016中将字符串中的重复项从表中删除)
本文介绍了如何在SQL Server 2016中将字符串中的重复项从表中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了一个包含一列字符串列的表。这些字符串由;分隔。现在,我想在拆分字符串后删除重复项。例如:
-----------
| w;w;e;e |
-----------
| q;r;r;q |
-----------
| b;n;n;b |
-----------
结果应为:
-------
| w;e |
-------
| q;r |
-------
| b;n |
-------
此外,它不应该是Select函数,而应该是delete函数(不是100%确定的)。因此原始表中的值将不再重复。
推荐答案
对于update语句,这将消除您的列的重复项:
update t
set col = stuff((
select distinct
';'+s.Value
from string_split(t.col,';') as s
for xml path (''), type).value('.','varchar(1024)')
,1,1,'');
在SQL SERVER 2016中,您可以使用string_split()和stuff() with select ... for xml path ('') method of string concatenation仅连接不同的值。
select
t.id
, t.col
, dedup = stuff((
select distinct
';'+s.Value
from string_split(t.col,';') as s
for xml path (''), type).value('.','varchar(1024)')
,1,1,'')
from t
dbfiddle演示:here
rextester demo:http://rextester.com/MAME55141;此demo在string_split()缺席的情况下使用Jeff Moden的CSV拆分器函数。
退货:
+----+---------+-------+
| id | col | dedup |
+----+---------+-------+
| 1 | w;w;e;e | e;w |
| 2 | q;r;r;q | q;r |
| 3 | b;n;n;b | b;n |
+----+---------+-------+
拆分字符串引用:
- Tally OH! An Improved SQL 8K "CSV Splitter" Function - Jeff Moden
- Splitting Strings : A Follow-Up - Aaron Bertrand
- Split strings the right way – or the next best way - Aaron Bertrand
string_split()in SQL Server 2016 : Follow-Up #1 - Aaron Bertrand
这篇关于如何在SQL Server 2016中将字符串中的重复项从表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
织梦狗教程
本文标题为:如何在SQL Server 2016中将字符串中的重复项从表中删除
基础教程推荐
猜你喜欢
- 在多列上分布任意行 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
