如何删除SSIS表达式中列中2个特殊字符之间的多个字符

问题描述

我想删除从“@”到“;”的多个字符在 SSIS 的派生列表达式中。 例如,

我的输入列值是,

enter image description here

并希望输出为,

enter image description here

注意:'@' 后的长度不固定。

已经在 sql 中尝试过,但想通过 SSIS 派生列表达式来实现。

解决方法

首先:请不要发布图片。我们更喜欢可复制和粘贴的样本数据。请尽量提供一个最小的、完整的和可重现的示例,最好作为 DDL、INSERT 和代码使用,就像我在这里为您所做的那样。

顺便提一下:如果您控制输入,则不应在一个字符串中混合信息...如果需要,请尝试使用“真实”文本容器,如 XML 或 JSON。

SQL-Server 不用于字符串操作。没有正则表达式或重复/嵌套模式匹配。所以我们将不得不使用递归/过程/循环方法。但是 - 如果性能不是那么重要 - 您可以使用 XML hack。

--DDL 和插入

DECLARE @tbl TABLE(ID INT IDENTITY,YourString VARCHAR(1000));
INSERT INTO @tbl VALUES('Here is one without'),('One@some comment;in here'),('Two comments@some comment;in here@here is the second;and some more text') 

--查询

SELECT t.ID,t.YourString,CAST(REPLACE(REPLACE((SELECT t.YourString AS [*] FOR XML PATH('')),'@','<!--'),';','--> ') AS XML) SeeTheIntermediateXML,'--> ') AS XML).value('.','nvarchar(max)') CleanedValue
FROM @tbl t

结果

+----+-------------------------------------------------------------------------+-----------------------------------------+
| ID | YourString                                                              | CleanedValue                            |
+----+-------------------------------------------------------------------------+-----------------------------------------+
| 1  | Here is one without                                                     | Here is one without                     |
+----+-------------------------------------------------------------------------+-----------------------------------------+
| 2  | One@some comment;in here                                                | One in here                             |
+----+-------------------------------------------------------------------------+-----------------------------------------+
| 3  | Two comments@some comment;in here@here is the second;and some more text | Two comments in here and some more text |
+----+-------------------------------------------------------------------------+-----------------------------------------+

简单的想法:

  • 使用一些字符串方法,我们可以将不需要的文本包裹在 XML 注释中。

看看这个

Two comments<!--some comment--> in here<!--here is the second--> and some more text
  • 使用 .value() 读取此 XML,将返回不带注释的内容。

提示 1:在替换中使用 '-->;' 以保留分号作为分隔符。

提示 2:如果字符串中的其他地方可能有分号 ;,您会在结果中看到 -->。在这种情况下,您需要针对结果字符串使用第三个 REPLACE()