【分享一个SQL函数】在SQL脚本中匹配使用特定分隔符分隔字符串的位置
来源:互联网 发布:淘宝首页放淘客链接 编辑:程序博客网 时间:2024/04/29 04:32
前段时间在工作中遇到一个问题:
abc,12,345,78
这个字符串统一通过逗号隔开,现在需要通过知道 12这个字符串的位置。
这种情况可以通过下面这个方法
/** 说明: 1)返回第一个满足的字串的位置 2)位置从0开始 */IF EXISTS(SELECT * FROM DBO.SYSOBJECTS WHERE ID=OBJECT_ID(N'[dbo].[func_IndexOfSubstrInDelimiterStr]') and xtype in (N'FN', N'IF', N'TF')) DROP FUNCTION [dbo].func_IndexOfSubstrInDelimiterStrGOCREATE function DBO.func_IndexOfSubstrInDelimiterStr(@str varchar(1024), --要分割的字符串@split varchar(10), --分隔符号@target varchar(100) --目标元素)returns INTasbegindeclare @location intdeclare @start intdeclare @next intdeclare @seed intdeclare @foundIndex intdeclare @foundflag bitselect @foundIndex = -1; set @str=ltrim(rtrim(@str))set @start=1set @seed=len(@split)select @foundflag = 0set @location=charindex(@split,@str)while @location > 0begin --有找到分隔符号,后面还有内容 SELECT @foundIndex = @foundIndex + 1 if substring(@str, @start, @location - @start) = @target begin select @foundflag = 1 break end set @start=@location+@seed set @location=charindex(@split,@str,@start)end--没有分隔符的情况if @location = 0 and @foundIndex = - 1begin if @str = @target SELECT @foundIndex = @foundIndex + 1, @foundflag = 1 endelseif @location = 0 and @foundIndex >= 0begin if substring(@str, @start, len(@str) - @start + 1) = @target begin select @foundIndex = @foundIndex + 1,@foundflag = 1 end end if @foundflag = 0 select @foundIndex = -1return @foundIndex endGO
使用样例:
SELECT DBO.func_IndexOfSubstrInDelimiterStr('13,2,12,3,16,1', ',', '1')
返回的结果是 5
如果涉及对执行的字符串进行更新替换,那么可以直接使用SQL 提供的STUFF函数
需要注意的是STUFF中第二个参数的下标是从1开始的, @newStr = STUFF(SrcStr, StartPos, length, strForReplace);
0 0
- 【分享一个SQL函数】在SQL脚本中匹配使用特定分隔符分隔字符串的位置
- 【SQL分享】去除字符串中连续的分隔符【经典】
- sql 字符串分隔函数
- sql字符串分隔函数
- SQL函数charindex用于匹配用逗号分隔的字符串
- 写一个函数讲一个字符串使用特定的分隔符分割后输出
- SQL得到一个字串在另一个字串组(以特定字符分隔)中的位置.
- SQL得到一个字串在另一个字串组(以特定字符分隔)中的位置
- sql里分隔字符串函数
- 在Sql中编写函数功能分隔字符串(同VB的split)
- Delphi中分隔字符串函数的使用
- 向数据库插入使用分隔符分隔(任意分隔符)的字符串脚本
- 分隔字符串的匹配
- sql 字符串分隔
- MS SQL 字符串分隔
- SQL Server 根据分隔符截取指定位置的子字符串
- SQL自定义函数split分隔字符串
- sql逗号分隔字符串转化成table的函数
- HTML 5 的自定义 data-* 属性和jquery的data()方法的使用
- gcj Round 1A 2015 Haircut
- UVa10010 - Where's Waldorf?
- HIHO_矩阵快速幂
- TCP和UDP的区别
- 【分享一个SQL函数】在SQL脚本中匹配使用特定分隔符分隔字符串的位置
- 强大的矢量图形库:Raphael JS
- 最长山峰序列
- 关于讯飞语音听写使用过程中出现的问题
- getopt 库的使用
- WebApp UI框架App.js的入门介绍和使用手册
- Linux 系统下安装jdk
- CentOS6.4_x64安装Oracle11g R2
- Npc行为-让我们的游戏世界更真实