如何仅从字符串中检索数值 [英] How to retrieve only numerical values from a string

查看:77
本文介绍了如何仅从字符串中检索数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从sql中的字符串中仅检索数值



我尝试过:



我尝试使用patindex但是我无法循环遍历循环

解决方案

你想要做什么将无法实现一些基本的PATINDEX,你需要为字符串运行一个循环并从中获取每个数值。以下面的SQL函数为例。



 创建  FUNCTION  NumbersFromString( @ string   VARCHAR  100 ))
RETURNS VARCHAR (< span class =code-digit> 100 )
AS
BEGIN
DECLARE @ loc INT
- 获取字符串中不是数字的第一个字母的位置。
SET @ loc = PATINDEX(' %[^ 0-9]%' @ string )
BEGIN
- - 迭代直到字符串中有一个非数字字母。
WHILE @ loc > 0
BEGIN
- 用''替换在该位置找到的字母。
SET @ string = STUFF( @ string @ loc 1 ' '
- 将位置设置为下一个字母。
SET @ loc = PATINDEX(' %[^ 0-9]%' @ string
END
END
- 返回结果。
RETURN ISNULL( @ string 0
END ;


另一种选择是使用Regex。请参阅:

TSQL正则表达式工作台 - 简单对话 [ ^ ]

如何部署正则表达式函数到SQL服务器 [ ^

How to retrieve only numerical values from a string in sql

What I have tried:

I tried with patindex but i can't able to iterate through the loop

解决方案

What you want to do will not be achieved by some basic PATINDEX, you will need to run a loop for the string and get every numeric value out of it. Consider the following SQL function as an example.

CREATE FUNCTION NumbersFromString (@string VARCHAR(100))
RETURNS VARCHAR(100)
AS
   BEGIN
     DECLARE @loc INT
     --Get the location of the first letter in the string that is not a number.
     SET @loc = PATINDEX('%[^0-9]%', @string )
       BEGIN
         --Iterate till there is a non-numeric letter in the string.
         WHILE @loc > 0
           BEGIN
             --Replace the letter found at the location with ''.
             SET @string = STUFF(@string , @loc, 1, '' )
             --Set location to next letter.
             SET @loc = PATINDEX('%[^0-9]%', @string )
           END
       END
       --Return result.
       RETURN ISNULL(@string, 0)
    END;


Another option is to use Regex. See:
TSQL Regular Expression Workbench - Simple Talk[^]
How to deploy the regular expression function to the SQL server[^]


这篇关于如何仅从字符串中检索数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆