首页 > 解决方案 > 如何在 SSIS 表达式的列中删除 2 个特殊字符之间的多个字符

问题描述

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

我的输入列值是,

在此处输入图像描述

并希望输出为,

在此处输入图像描述

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

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

标签: tsqlssismsbi

解决方案


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

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

SQL-Server 不适用于字符串操作。没有 RegEx 或重复/嵌套模式匹配。所以我们将不得不使用递归/过程/循环的方法。但是 - 如果性能不是那么重要 - 您可能会使用 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
      ,CAST(REPLACE(REPLACE((SELECT t.YourString AS [*] FOR XML PATH('')),'@','<!--'),';','--> ') 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
  • 使用内容读取此 XML.value()将返回不带注释。

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

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


推荐阅读