一些字符串是由"-"连接字符连接。
想以这个连接字符"-"对字符串时行截取前后字符。
可以写一个自定义函数:
SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO-- =============================================-- 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))ASBEGIN 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'') RETURNENDGO
例子:
下面有一临时表,存储一些字符:
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
SELECT [ID],[Strings],[Front],[Back] FROM #TCROSS APPLY [dbo].[svf_CutOutStringWithHyphen]([Strings])