一些字符串是由”-“连接字符连接。
想以这个连接字符”-“对字符串时行截取前后字符。
可以写一个自定义函数:
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
例子:
下面有一临时表,存储一些字符:
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
现使用上面的自定义函数对临时表中[string]字符进行分割。得到的结果如下:
select [id],[strings],[front],[back] from #t cross apply [dbo].[svf_cutoutstringwithhyphen]([strings])