【问题标题】:SQL Server split sting based on patternsSQL Server 根据模式拆分字符串
【发布时间】:2019-11-04 21:51:59
【问题描述】:

我正在尝试根据第一个字符和最后一个字符的两种模式拆分特定字符串,第一个字符必须是任何数值,最后一个字符是逗号。

我正在使用 patindexsubstringcharindex 函数,但它们只提供一行。

这是我正在处理的查询:

DECLARE @x varchar(max) = 'In the vocational certificate category, if served as laundry/dry cleaning specialist, 2 semester hours in treatment of fabrics (stain removing, spotting, solutions), 2 in laundry equipment operation, 2 in dry cleaning, 3 in small business management, 3 in introduction to business, 3 in supply management, and 3 in business report writing.'
   Declare @extract varchar(max) = ''
   set @extract = substring(@x, patindex('%[0-99] [i]%[,] %', @x), (LEN(@x)) -  CHARINDEX('%[0-99] [i]%[,] %', REVERSE(@x))) 
   select @extract 

结果是这样的: 洗衣设备操作2名,干洗2名,小企业管理3名,商业介绍3名,供应管理3名,商业报告撰写3名。

有没有办法在列中获取结果?像这样:

  • 2在洗衣设备操作中
  • 2中干洗
  • 3 小企业管理

...

【问题讨论】:

  • SQL Server 不是你的朋友。我什至不明白其中的逻辑,如果我说实话,但是,如果你需要存储不同的值,那么INSERT它之前这样做。如果您确实需要将这些字符串解析为其他内容,则最好使用某种支持 REGEX 的 CLR 函数来“拆分”它。
  • 但您不想要关于“2 个学期小时......”的部分。似乎第一遍是根据逗号分隔符将字符串切碎。这是否有效取决于逗号是否也可以在其他地方并且不能解释为分隔符。一旦你有了一级拆分,你需要定义逻辑来忽略我第一次提到的那个位。也许这可以按位置完成?
  • 谢谢你们!

标签: sql-server string function design-patterns split


【解决方案1】:

虽然我同意 sql server 是适合这项工作的错误工具,但它是可行的。您可以使用可在此处找到的 DelimitedSplit8K_LEAD 函数。 https://www.sqlservercentral.com/articles/reaping-the-benefits-of-the-window-functions-in-t-sql-2

那么处理这个就很简单了。请注意,这不会返回“3 in business report writing”,因为这不符合您“最后一个值是逗号”的规则。

DECLARE @x varchar(1000) = 'In the vocational certificate category, if served as laundry/dry cleaning specialist, 2 semester hours in treatment of fabrics (stain removing, spotting, solutions), 2 in laundry equipment operation, 2 in dry cleaning, 3 in small business management, 3 in introduction to business, 3 in supply management, and 3 in business report writing.'

select MyResult = ltrim(s.Item)
from dbo.DelimitedSplit8K_LEAD(@x, ',') s
where left(ltrim(s.Item), 1) like '%[0-9]%'
order by s.ItemNumber

上面的查询将返回。

2 semester hours in treatment of fabrics (stain removing
2 in laundry equipment operation
2 in dry cleaning
3 in small business management
3 in introduction to business
3 in supply management

【讨论】:

  • 非常感谢 Sean Lange,非常感谢您的帮助,这正是我所需要的。
猜你喜欢
  • 1970-01-01
  • 2017-05-07
  • 2014-06-23
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 2018-11-10
  • 1970-01-01
相关资源
最近更新 更多