如何将String SQL从拆分为?

时间:2019-06-11 10:27:10

标签: sql sql-server tsql

如何从sql中拆分一个值?

EX:列SQL

现在,我想拆分为

代码:

declare @ND nvarchar(max)= N'AA (AA11) [37100]'
select substring(@ND,1,patindex('%[0-9]%',@ND)-2) as Name
      ,substring(@ND,patindex('%[0-9]%',@ND),len(@ND)) as Number

4 个答案:

答案 0 :(得分:1)

Declare @t table (fullname varchar(50))

insert into @t values ('AA [1111]')
insert into @t values ('BB(15CC) [2222]')

select 
    fullname,
    substring(fullname,1,CHARINDEX('[',fullname)-1) Name,
    replace(substring(fullname,CHARINDEX('[',fullname)+1,len(fullname)),']','') as number 
from @t

答案 1 :(得分:1)

在示例数据中,最后6个字符始终是带数字的方括号。如果总是这样,则可以使用更简单的逻辑:

select left(fullname, len(fullname) - 7),
       left(right(fullname, 5), 4)
from @t;

Here是db <>小提琴。

对于更一般的情况,我还要处理字符串中没有[而不会产生错误的情况:

select left(fullname, charindex('[', fullname + '[') - 1),
       replace(stuff(fullname, 1, charindex('[', fullname + '['), ''), ']', '')
from @t;

Here是另一个db <>小提琴。

答案 2 :(得分:0)

您可以通过使用CHARINDEX()REPLACE()LEN()SUBSTRING()函数来做到这一点

SELECT Str FullName,
       REPLACE(Str, SUBSTRING(Str, CHARINDEX('[', Str), CHARINDEX(']', Str)), '') Name,
       SUBSTRING(Str, CHARINDEX('[', Str) + 1, LEN(Str) - CHARINDEX('[', Str)-1) Number
FROM (VALUES('BBB(15CC)[222]'), ('AA[1111]')) T(Str);

OR

;WITH CTE AS
(
  SELECT Str FullName,
         LEFT(Str, CHARINDEX('[', Str) -1) Name
  FROM (VALUES('BBB(15CC)[222]'), ('AA[1111]')) T(Str)
)
SELECT FullName,
       Name,
       REPLACE(REPLACE(FullName, Name + '[', ''), ']', '') Number
FROM CTE;

返回:

+----------------+-----------+--------+
|    FullName    |   Name    | Number |
+----------------+-----------+--------+
| BBB(15CC)[222] | BBB(15CC) |    222 |
| AA[1111]       | AA        |   1111 |
+----------------+-----------+--------+

答案 3 :(得分:0)

使用Xml转换,我们可以获得预期的结果

Declare @t table (fullname varchar(50))
insert into @t values ('AA [1111]')
insert into @t values ('BB(15CC) [2222]')


SELECT DISTINCT Fullname,
       Split.a.value('/S[1]','nvarchar(100)') AS Name,
       Split.a.value('/S[2]','nvarchar(100)') AS Number
FROM
(
SELECT Fullname,
        CAST('<S>'+REPLACE(REPLACE(REPLACE(Fullname,' ','</S><S>')+'</S>','[',''),']','') AS XML ) AS FullnameData
FROM @t
)AS A
CROSS APPLY FullnameData.nodes('S') AS Split(a)

结果

Fullname            Name        Number
----------------------------------------
AA [1111]           AA          1111
BB(15CC) [2222]     BB(15CC)    2222