简体   繁体   中英

T-SQL / Find all dots in a column

I have query like that :

DECLARE @TABLE TABLE (
    ID int primary key identity(1,1),
    CODE nvarchar(max)
);
INSERT INTO @TABLE VALUES ('320.01.001'),('320.01.002'),('320.001.002'),('320.01.002.0003.0002')
SELECT * FROM @TABLE 

Result:

在此处输入图片说明

I want to count of dots in a column .

My excepted result:

在此处输入图片说明

A pretty simple method is:

select t.*, s.num_dots
from @table t cross apply
     (select count(*) - 1 as num_dots
      from string_split(t.code, '.') s
     ) s;

A more traditional method uses the difference between the lengths of two strings:

select t.*,
       len(t.code) - len(replace(t.code, '.', '')) as num_dots
from @table t;

I actually do not have a sense of which of these is faster. If I had to guess, I would guess the second, but if performance is an issue, you should test the two versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM