【问题标题】:How to extract strings between third and fourth special characters in TSQL如何在 SQL 中提取第三个和第四个特殊字符之间的字符串
【发布时间】:2017-05-02 16:15:15
【问题描述】:
字符串 1:1*2*3*4*5*6* 字符串 2:1*2*3*40*500*6* 字符串 3:1*2*3*400*5*600* 字符串 4:1*2*3*4000*50*6000* 目标是返回以下字符串: 字符串 1:4 字符串 2:40 字符串 3:400 字符串 4:4000

【问题讨论】:

  • 目标不应该是在单个列中存储多个值
  • @juergend 对不起,我不明白你的意思?
  • 他的意思是你不应该在一个数据库字段中存储多个值 - 这是非常糟糕的数据库设计。
  • 这也是一个更适合应用程序代码而非数据库代码解决方案的问题(因为 SQL 中的文本操作不是很好)。
  • @DigiFriend...同意。但这是现有的设计。所以我现在无法真正改变任何事情。

标签: sql sql-server


【解决方案1】:

几乎任何解析/拆分函数都可以。这种内联方法不需要 UDF,并且还返回项目序列。

示例

Declare @YourTable table (ID int,SomeCol varchar(500))
Insert Into @YourTable values
(1,'1*2*3*4*5*6*'),
(2,'1*2*3*40*500*6*'),
(3,'1*2*3*400*5*600*'),  
(4,'1*2*3*4000*50*6000*')

Select A.ID
      ,B.RetVal
 From  @YourTable A
 Cross Apply (
                Select RetSeq = Row_Number() over (Order By (Select null))
                      ,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
                From  (Select x = Cast('<x>' + replace((Select replace(A.SomeCol,'*','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A 
                Cross Apply x.nodes('x') AS B(i)
             ) B
 Where RetSeq=4

退货

ID  RetVal
1   4
2   40
3   400
4   4000

【讨论】:

  • 非常感谢。这很有帮助!
  • @Solution 很高兴它有帮助
【解决方案2】:

在 SQL Server 2016+ 中,您可以使用 string_split()

在 2016 年之前的 SQL Server 中,使用 Jeff Moden 的 CSV 拆分器表值函数:

select 
    str
  , s.ItemNumber
  , s.Item
from t
  cross apply dbo.DelimitedSplit8k(t.str,'*') s
where s.ItemNumber = 4

rextester 演示:http://rextester.com/HYCF1752

返回:

+---------------------+------------+------+
|         str         | ItemNumber | Item |
+---------------------+------------+------+
| 1*2*3*4*5*6*        |          4 |    4 |
| 1*2*3*40*500*6*     |          4 |   40 |
| 1*2*3*400*5*600*    |          4 |  400 |
| 1*2*3*4000*50*6000* |          4 | 4000 |
+---------------------+------------+------+

拆分字符串参考:

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-27
  • 1970-01-01
  • 2014-06-08
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 2021-09-13
相关资源
最近更新 更多