数据库教程:以连接字符截取字符串

一些字符串是由"-"连接字符连接。 想以这个连接字符"-"对字符串时行截取前后字符。 可以写一个自定义函数: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO — — Author: Insus.NET — Create date: 2019-0 …

一些字符串是由”-“连接字符连接。

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

可以写一个自定义函数:

 

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

 

需要了解更多数据库技术:以连接字符截取字符串,都可以关注数据库技术分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/dtteaching/626304.html

(0)
上一篇 2021年5月26日
下一篇 2021年5月26日

精彩推荐