【问题标题】:Picking Number String out of Text String从文本字符串中挑选数字字符串
【发布时间】:2015-10-03 14:12:30
【问题描述】:

我有一个文本字段,其中包含可变长度的表单条目:

"house:app.apx&resultid=1234,clientip"

或

"tost:app.apx&resultid=123,clientip"

或

"airplane:app.apx&resultid=123489,clientip"

无论字符串的其余部分如何,我都在尝试找出resultid='...',clientip 之间的数字。所以在这个例子中,它将是数字:

1234
123
12389

resultid='...',clientip 形式的字符串部分始终保持不变,只是数字的长度可以变化。

【问题讨论】:

  • 将substring 与charindex 一起使用。
  • 您是从数据库中检索此数据还是尝试在数据库中的存储过程中执行此操作?

标签: sql tsql sql-server-2005


【解决方案1】:

这应该可行:

-- test data
DECLARE @t table (String VARCHAR(100))
INSERT @t VALUES 
('"house:app.apx&resultid=1234,clientip"'),
('"tost:app.apx&resultid=123,clientip"'),
('"airplane:app.apx&resultid=123489,clientip"')


SELECT 
  SUBSTRING(
    String, 
    CHARINDEX('resultid=', String) + 9, 
    CHARINDEX(',clientip', String) - CHARINDEX('resultid=', String) - 9
  ) 
FROM @t

-- Result
1234
123
123489

您可能希望添加某种检查,以免处理空值。

【讨论】:

    【解决方案2】:

    使用字符串函数可以像下面这样完成

    select SUBSTRING("house:app.apx&resultid=1234,clientip",
                               CHARINDEX('=',"house:app.apx&resultid=1234,clientip"),
                               CHARINDEX(',',"house:app.apx&resultid=1234,clientip") - CHARINDEX('=',"house:app.apx&resultid=1234,clientip"));
    

    【讨论】:

      【解决方案3】:

      类似于@Rahul,但有些不同,使用 PATINDEX:

      declare @start varchar(20) = '%resultid=%'
      declare @end varchar(20) = '%,clientid%'
      SELECT REPLACE(REPLACE(SUBSTRING(Field,PATINDEX(@start,Field)),@start,''),@end,'')
      

      【讨论】:

        猜你喜欢
        • 2021-12-27
        • 1970-01-01
        • 2015-08-06
        • 2014-09-21
        • 2012-02-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-18
        • 1970-01-01
        相关资源
        最近更新 更多