SSIS提取字符之间的字符串

时间:2017-03-13 23:06:16

标签: sql-server ssis

我的源SQL表中有以下列

**Name**  |**Locations** 
----------------------------
Tom       |;1500002;3940000;49599;'USA';
<p>Gerry  |;100000;23;45222;3445;'Canada';4245;'Australia';'Singapore';

我需要在单引号之间提取字符串'并使用SSIS添加新行,如下所示。

**Name**|**Locations**
------------------------
Tom     |USA
Gerry   |Canada
Gerry   |Australia
Gerry   |Singapore

请让我知道如何实现它。

2 个答案:

答案 0 :(得分:1)

借助CROSS APPLY和几乎任何分割/分析功能

如果2016年您可以使用String_Split()

Select A.Name
      ,Locations = substring(B.Value,2,len(B.Value)-2)
 From  @YourTable A
 Cross Apply String_Split(A.Locations,';') B
 Where B.Value like '''%'''

如果不是2016

Declare @YourTable table (Name varchar(25),Locations varchar(100))
Insert Into @YourTable values 
('Tom',';1500002;3940000;49599;''USA'';'),
('Gerry',';100000;23;45222;3445;''Canada'';4245;''Australia'';''Singapore'';')

Select A.Name
      ,Locations = substring(B.RetVal,2,len(B.RetVal)-2)
 From  @YourTable A
 Cross Apply [dbo].[udf-Str-Parse](A.Locations,';') B
 Where B.RetVal like '''%'''

两者都会返回

Name    Locations
Tom     USA
Gerry   Canada
Gerry   Australia
Gerry   Singapore

感兴趣的UDF

CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (  
    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(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as X
    Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')

答案 1 :(得分:0)

首先,这种操作不需要使用SSIS ,您可以使用Simple SQL查询来完成。 (喜欢@JohnCappelletti建议)

但是这样你可以使用SSIS来做到这一点:

首先添加OLEDB连接管理器

  1. 添加DataFlowTask
  2. DataFlow任务中的
  3. 添加OLEDB Source - &gt; Script Component - &gt; OLEDB Destination
  4. Script Component标记Location列中输入并添加与输入类型和长度相似的输出列OutLocation
  5. 在脚本中编写以下代码:

    If Not Row.Location_IsNull AndAlso _
       Not String.IsnullOrEmpty(Row.Location) Then
    
       Dim strTemp = Row.Location.Substring(0,Row.Location.IndexOf("'") - 1)
    
       strTemp = strTemp.Substring(0,strTemp.Index("'") - 1)
    
       Row.OutLocation = StrTemp
    
       Else
    
       Row.OutLocation_IsNull = True
    
    End If
    
  6. 将地理outLocation映射到OLEDB Destination

  7. 中的目的地列