How to split string with delimiter and get the first value

Dor*_*eka 0 sql t-sql sql-server

I have the following query where I have a table which is storing from information with a delimiter

SQL version - Microsoft SQL Azure (RTM) - 12.0.2000.8

DECLARE @commanTable TABLE
(
  CommaId NVARCHAR(MAX),
  Name NVARCHAR(500)
)

DECLARE @commanTable1 TABLE
(
   CommaId INT,
   Name NVARCHAR(500)
)

INSERT INTO @commanTable VALUES ('2324205.3933251.7336404', 'Test1'), 
('2324206.3933252.7336405', 'Test2')

INSERT INTO @commanTable1 (CommaId, Name)
SELECT  value, Name
FROM   @commanTable CROSS APPLY STRING_SPLIT(CommaId,'.');

SELECT * FROM @commanTable1
Run Code Online (Sandbox Code Playgroud)

Getting the following results

在此处输入图片说明

Where I need the results to be

在此处输入图片说明

Squ*_*rel 5

如果您只对第一个值感兴趣,则不需要使用STRING_SPLIT(). 您可以简单地用于charindex()查找第一个分隔符并用于left()提取它

SELECT *, left(CommaId, charindex('.', CommaId) - 1)
FROM   @commanTable
Run Code Online (Sandbox Code Playgroud)

编辑:如果你总是想要第 n 个值,你可以做一个级联 charindex()。前提是n不是太大。否则使用我在评论中提供的功能。

SELECT  *, 
        item1 = left(CommaId, p1.p - 1),
        item2 = substring(CommaId, p1.p + 1, p2.p - p1.p - 1)
FROM    @commanTable t
        cross apply
        (
            select  p = charindex('.', CommaId)
        ) p1
        cross apply
        (
            select  p = charindex('.', CommaId, p1.p + 1)
        ) p2
Run Code Online (Sandbox Code Playgroud)