在SQL Server 2012中选择引号(“)

时间:2014-07-11 20:28:48

标签: sql sql-server-2012

我有一个表在一列中包含ID,在第二列中包含一个字符串,如下所示。

COLUMN01               COLUMN02
----------------------------------------------------------------------------------    
1                      abc"11444,12,13"efg"14,15"hij"16,17,18,19"opqr
2                      ahsdhg"21,22,23"ghshds"24,25"fgh"26,27,28,28"shgshsg
3                      xvd"3142,32,33"hty"34,35"okli"36,37,38,39"adfd

现在我希望得到以下结果

COLUMN01               COLUMN02
-----------------------------------------------------------    
1                      11444,12,13,14,15,16,17,18,19
2                      21,22,23,24,25,26,27,28,28
3                      3142,32,33,34,35,36,37,38,39

我该怎么做?

非常感谢

2 个答案:

答案 0 :(得分:0)

我知道你想用SQL做。但是我有几乎相同的问题,并使用PHP或其他语言将此数据转换为字符串,而不是解析是一种方法。例如,您可以在将数据接收到字符串后使用此类代码。

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

有关详细信息,您可能需要查看我检索到该功能的帖子:Remove all special characters from a string

正如我所说,这是一种简单的方法,我希望这可以提供帮助。

答案 1 :(得分:0)

这是一种方式(可能不是最好的,但似乎有效)。我不是SQL大师...

首先,创建此SQL函数。它来自:Extract numbers from a text in SQL Server

create function [dbo].[GetNumbersFromText](@String varchar(2000))
returns table as return
(
  with C as
  (
    select cast(substring(S.Value, S1.Pos, S2.L) as int) as Number,
           stuff(s.Value, 1, S1.Pos + S2.L, '') as Value
    from (select @String+' ') as S(Value)
      cross apply (select patindex('%[0-9]%', S.Value)) as S1(Pos)
      cross apply (select patindex('%[^0-9]%', stuff(S.Value, 1, S1.Pos, ''))) as S2(L)
    union all
    select cast(substring(S.Value, S1.Pos, S2.L) as int),
           stuff(S.Value, 1, S1.Pos + S2.L, '')
    from C as S
      cross apply (select patindex('%[0-9]%', S.Value)) as S1(Pos)
      cross apply (select patindex('%[^0-9]%', stuff(S.Value, 1, S1.Pos, ''))) as S2(L)
    where patindex('%[0-9]%', S.Value) > 0
  )
  select Number
  from C
)

然后,你可以做这样的事情来获得你要求的结果。请注意,为了清楚起见,我将查询分为3部分。而且,显然,您不需要声明表变量并将数据插入其中。

DECLARE @tbl
TABLE (
    COLUMN01 int,
    COLUMN02 varchar(max)
)
INSERT INTO @tbl VALUES (1, 'abc"11444,12,13"efg"14,15"hij"16,17,18,19"opqr')
INSERT INTO @tbl VALUES (2, 'ahsdhg"21,22,23"ghshds"24,25"fgh"26,27,28,28"shgshsg')
INSERT INTO @tbl VALUES (3, 'xvd"3142,32,33"hty"34,35"okli"36,37,38,39"adfd')

SELECT COLUMN01, SUBSTRING(COLUMN02, 2, LEN(COLUMN02) - 1) as COLUMN02 FROM
(
    SELECT COLUMN01, REPLACE(COLUMN02, ' ', '') as COLUMN02 FROM
    (
        SELECT COLUMN01, (select ',' + number as 'data()' from dbo.GetNumbersFromText(Column02) for xml path('')) as COLUMN02 FROM @tbl
    ) t
) tt
GO

输出:

COLUMN01   COLUMN02
1        11444,12,13,14,15,16,17,18,19
2        21,22,23,24,25,26,27,28,28
3        3142,32,33,34,35,36,37,38,39