以连接字符截取字符串

一些字符串是由"-"连接字符连接。

想以这个连接字符"-"对字符串时行截取前后字符。

可以写一个自定义函数:

 

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:      Insus.NET
-- Create date: 2019-05-27
-- Update date: 2019-05-27
-- Description: 截取字符串
-- =============================================
CREATE FUNCTION [dbo].[svf_CutOutStringWithHyphen]
(
    @string NVARCHAR(MAX)
)
RETURNS @Table TABLE([Front] NVARCHAR(MAX),[Back] NVARCHAR(MAX))
AS
BEGIN  
   DECLARE @hyphen VARCHAR(1) = N'-'
    IF @string LIKE '%'+ @hyphen +'%'
    BEGIN
    DECLARE @hyphen_position INT = CHARINDEX(@hyphen, @string)
        INSERT INTO @Table ([Front],[Back])
        SELECT SUBSTRING(@string, 1, @hyphen_position - 1) AS _From,
               SUBSTRING(@string, @hyphen_position + 1, LEN(@string)- @hyphen_position) AS _To    
    END
    ELSE
    INSERT INTO @Table ([Front],[Back]) VALUES(N'',N'')
    RETURN
END
GO
Source Code

 

例子:

下面有一临时表,存储一些字符:

 

CREATE TABLE #T ([ID] INT, [Strings] NVARCHAR(40))
INSERT INTO #T([ID],[Strings]) VALUES (1,'B-Q'),(2,'23-45'),(3,'H-P'),(4,'ADF'),(5,'ADSF-ASDF-ASDF'),(6,'-ADF-ADF-'),(7,'-SFDG-KLJ-QER-'),(8,'shg-'),(9,'-sdfgs')

SELECT [ID],[Strings] FROM #T
Source Code


现使用上面的自定义函数对临时表中[String]字符进行分割。得到的结果如下:

 

SELECT [ID],[Strings],[Front],[Back] FROM #T
CROSS APPLY 
[dbo].[svf_CutOutStringWithHyphen]([Strings])
Source Code

 

posted @ 2019-05-27 08:51 Insus.NET 阅读(...) 评论(...) 编辑 收藏