• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

sql中取字符串中的数字语句_MySQL

mysql 搞代码 4年前 (2022-01-09) 20次浏览 已收录 0个评论

gaodaima.com

one:
declare @s varchar(20)
declare @i varchar(20)
set @i=”
set @s=’新会员必须购买350元产品’
while PATINDEX (‘%[0-9]%’, @s)>0
begin
set @i=@i+substring(@s,PATINDEX (‘%[0-9]%’, @s),1)
set @s=stuff(@s,1,PATINDEX (‘%[0-9]%’, @s),”)
end
select @i

300

two:
declare @a table(id int identity(1,1),a varchar(100))
insert @a select ‘新会员必须购买350元产品’
union all select ‘新店首次定货必须满20000元’

select left(right(a,len(a)-patindex(‘%[0-9]%’,a)+1),len(right(a,len(a)-patindex(‘%[0-9]%’,a)+1))-1) from @a

上在的

select substring(所查询字符串,patindex(‘%[^0-9][0-9]%’,所查询字符串)+1,patindex(‘%[0-9][^0-9]%’,所查询字符串)-patindex(‘%[^0-9][0-9]%’,所查询字符串)) 这个只能查询第一次在字符串出现的数字串

那么如果出现字符串什么样子的呢 sss8989sss http://www.hzhuti.com ss8989ss8989ss8989 7879aafds789 432432432543534 应该怎么取呢

实例

代码如下 复制代码
create function fn_GetNum(@s varchar(8000))
returns varchar(8000)
as
begin
select @s = stuff(stuff(@s, 1, patindex(‘%[0-9, .]%’, @s) – 1, ”),
patindex(‘%[^0-9, .]%’, stuff(@s, 1, patindex(‘%[0-9, .]%’, @s) – 1, ”)),
len(@s), ”)
return @s
end

declare @t table(s varchar(8000))

insert @t select ‘aaa11112bbb’
union all select ‘ccc212sss’
union all select ‘sss21a’

select dbo.fn_GetNum(s) as result from @t

select substring(s,patindex(‘%[^0-9][0-9]%’,s)+1,patindex(‘%[0-9][^0-9]%’,s)-patindex(‘%[^0-9][0-9]%’,s)) from @t

/*功能:获取字符串中的字母*/
CREATE FUNCTION dbo.F_Get_STR (@S VARCHAR(100))
RETURNS VARCHAR(100)
AS
BEGIN
WHILE PATINDEX(‘%[^a-z]%’,@S)>0
BEGIN
set @s=stuff(@s,patindex(‘%[^a-z]%’,@s),1,”)
END
RETURN @S
END
GO
–测试
select dbo.F_Get_STR(‘测试ABC123ABC’)

GO

/*
功能:获取字符串中的数字
*/
create function dbo.F_Get_Number (@S varchar(100))
returns int
AS
begin
while PATINDEX(‘%[^0-9]%’,@S)>0
begin
set @s=stuff(@s,patindex(‘%[^0-9]%’,@s),1,”)
end
return cast(@S as int)
end
–测试
—select dbo.F_Get_Number(‘测试AB3C123AB5C’)
GO

这样之后不管你是那种组合我们都可本文来源gaodai#ma#com搞@@代~&码网以方便的把字符中的数字全部取出来。

更多详细内容请查看:http://www.111cn.net/database/mssqlserver/42376.htm

gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:sql中取字符串中的数字语句_MySQL

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址