sql - SQL Server pull out only data after = OR only the numerics
问题描述
It seems that a regular expression would be ideal, yet some team members are not fond of regex...
Problem: Data in a column (from a mainframe flat file import) looks like 2 different ways
BreakID = 83823737237
OR
MFR BreakID=482883
Thus, the differences are a space before numerics, length of both the alphacharacter before the equals varies and finally the length of the numbers will vary.
Seems I have a few approaches,
1. Everything after the = sign , and trim ?
2. regex , get only the numerics?
So I found this code, in which I assume PATINDEX is standard way of doing regex in -tsql ? what is "string" in this?
SELECT SUBSTRING(string, PATINDEX('%[0-9]%', string), PATINDEX('%[0-9][^0-9]%', string + 't') - PATINDEX('%[0-9]%',
string) + 1) AS Number
How would this be solved with best practices?
解决方案
答案与 scsimon 略有不同。当我必须抓住字符串末尾的 vals 时,我通常会走这条路。您反转字符串并抓取键值的第一个实例的位置(在本例中为“=”)。使用 charindex 获取该位置,然后使用该 charindex 值获取 RIGHT() 字符。
DECLARE @val1 VARCHAR(100) = 'BreakID = 83823737237'
DECLARE @val2 VARCHAR(100) = 'MFR BreakID=482883'
SELECT
LTRIM(RTRIM(RIGHT(@val1, CHARINDEX('=', REVERSE(@val1), 0)-1)))
,LTRIM(RTRIM(RIGHT(@val2, CHARINDEX('=', REVERSE(@val2), 0)-1)))
如果你有奇怪的情况,这个解决方案会很好,比如如果你有一家公司SQL=Cool
在你的数据中调用它并且它需要一个 ID:
'SQL=CoolID = 12345'
你还想得到 12345。
推荐阅读
- python - Ansible 无法从 URL 中提取 json,但 Curl 可以。我错过了什么?
- html - 正则表达式获取 src 包含文本的 img 标签
- c - CGO:处理 SIGTERM / SIGABRT
- go - 任意结构和 nil 之间的相等性检查何时可以为真?
- android - 带有导航菜单系统的模型的 Android 详细视图
- python - 如何在 CSES 问题计数室中克服 Python 的 TLE(超出时间限制)?
- javascript - Stripe 从基于令牌的费用迁移到基于支付意图的费用
- javascript - React Router 显示空白页面,直到刷新
- r - 在 R 中使用文本分析/文本挖掘对齐两个数据库
- android - 在运行时选择 android 库版本