SQL:如何在所有行中获取列中的所有不同的字符

前端之家收集整理的这篇文章主要介绍了SQL:如何在所有行中获取列中的所有不同的字符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
sql Server中是否有一种优雅的方法来查找所有行中的单个varchar(50)列中的所有不同的字符?

奖金积分,如果它可以做没有光标:)

例如,说我的数据包含3行:

productname
-----------
product1
widget2
nicknack3

字符的不同库存将是“productwigenka123”

解决方法

鉴于您的列是varchar,这意味着它只能存储代码0到255中的任何代码页的字符.如果只使用32-128 ASCII码范围,那么可以简单的看看你是否有任何一个字符32-128.以下查询确实如此,在sys.objects.name中查找:
with cteDigits as (
    select 0 as Number
    union all select 1 as Number
    union all select 2 as Number
    union all select 3 as Number
    union all select 4 as Number
    union all select 5 as Number
    union all select 6 as Number
    union all select 7 as Number
    union all select 8 as Number
    union all select 9 as Number),cteNumbers as (
    select U.Number + T.Number*10 + H.Number*100 as Number
    from cteDigits U
    cross join cteDigits T
    cross join cteDigits H),cteChars as (
    select CHAR(Number) as Char
    from cteNumbers 
    where Number between 32 and 128)
select cteChars.Char as [*]
from cteChars
cross apply (
    select top(1) *
    from sys.objects
    where CHARINDEX(cteChars.Char,name,0) > 0) as o
for xml path('');

猜你在找的MsSQL相关文章