当前位置: 移动技术网 > IT编程>数据库>MSSQL > 以连接字符截取字符串

以连接字符截取字符串

2019年05月28日  | 移动技术网IT编程  | 我要评论

启东市卫生局,重生之名门锦翠,异世龙逍遥下载

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

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

可以写一个自定义函数:

 

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])

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网