[英]Extract string using SQL Server 2012
I have a string in the form of我有一个字符串形式
<div>#FIRST#12345#</div>
How do I extract the number part from this string using T-SQL in SQL Server 2012?如何在 SQL Server 2012 中使用 T-SQL 从此字符串中提取数字部分? Note the number has variable length
请注意,该数字具有可变长度
Shooting from the hip due to a missing minimal reproducible example .由于缺少最小的可重现示例而从臀部拍摄。
Assuming that it is XML data type column.假设是XML数据类型列。
SQL SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, xmldata XML);
INSERT INTO @tbl (xmldata) VALUES
('<div>#FIRST#12345#</div>'),
('<div>#FIRST#770770#</div>');
-- DDL and sample data population, end
SELECT t.*
, LEFT(x, CHARINDEX('#', x) - 1) AS Result
FROM @tbl t
CROSS APPLY xmldata.nodes('/div/text()') AS t1(c)
CROSS APPLY (SELECT REPLACE(c.value('.', 'VARCHAR(100)'), '#FIRST#' ,'')) AS t2(x);
Output Output
+----+---------------------------+--------+
| ID | xmldata | Result |
+----+---------------------------+--------+
| 1 | <div>#FIRST#12345#</div> | 12345 |
| 2 | <div>#FIRST#770770#</div> | 770770 |
+----+---------------------------+--------+
Using just t-sql string functions you can try:仅使用 t-sql 字符串函数,您可以尝试:
create table t(col varchar(50))
insert into t select '<div>#FIRST#12345#</div>'
insert into t select '<div>#THIRD#543#</div>'
insert into t select '<div>#SECOND#3690123#</div>'
select col,
case when p1.v=0 or p2.v <= p1.v then ''
else Substring(col, p1.v, p2.v-p1.v)
end ExtractedNumber
from t
cross apply(values(CharIndex('#',col,7) + 1))p1(v)
cross apply(values(CharIndex('#',col, p1.v + 1)))p2(v)
Output: Output:
Caveat, this doesn't handle any "edge" cases and assumes data is as described.警告,这不处理任何“边缘”情况,并假定数据如所描述的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.