SQL Server : returning text only in the brackets

时间:2018-02-26 17:43:17

标签: sql sql-server tsql pattern-matching database-normalization

I have text stored in column; in hundreds of rows. The text is VARCHAR and anywhere from 500-5000 characters. I want to return only the numbers between 2 brackets.

So here's an example

abcd(22135)  
hhgygas(52142)dijijijs  
whatisthis(33234) i have no idea (22342)

And the result should be

22135  
52142  
33234  
22342  

2 个答案:

答案 0 :(得分:0)

您可以使用UDF和CROSS APPLY来获取所有值。

create table tbl (txt varchar(max));
insert into tbl values
('abcd(22135)'), 
('hhgygas(52142)dijijijs'),
('whatisthis(33234) i have no idea (22342)');
GO
create function dbo.getValues(@txt varchar(max)) 
returns @t table
(val varchar(20))
as
begin
    declare @p1 int, @p2 int;
    set @p1 = 0;
    set @p2 = 0;

    while charindex('(', @txt, @p2) <> 0
    begin
        set @p1 = charindex('(', @txt, @p2);
        if @p1 = 0 return;
        set @p2 = charindex(')', @txt, @p1);
        if @p2 = 0 return;
        insert into @t values(substring(@txt, @p1 + 1, @p2 - @p1 - 1));
    end

    return;
end
GO
select f.val
from   tbl
cross apply dbo.getValues(tbl.txt) f
GO
| val   |
| :---- |
| 22135 |
| 52142 |
| 33234 |
| 22342 |

dbfiddle here

答案 1 :(得分:0)

获取ngrams2b的副本,您可以执行此操作:

-- Sample data
DECLARE @table TABLE (someid int identity, col1 varchar(max));
INSERT @table VALUES
('abcd(22135)'),
('hhgygas(52142)dijijijs'),
('whatisthis(33234) i have no idea (22342)'),
('nothing to see here');

-- Solution    
SELECT 
  t.someid,
  numbers = 
    substring(t.col1, position+1,nullif(charindex(')', t.col1, position+1),0)-position-1)
FROM @table t
CROSS APPLY dbo.ngrams2b(t.col1,1)
WHERE token = '(';

<强>结果

someid      numbers
----------- --------
1           22135
2           52142
3           33234
3           22342