简体   繁体   English

T-SQL中的正则表达式

[英]Regular expression in T-SQL

I have the next issue, there is table with column data (type - nvarchar), this column can contains any characters, I need selected only data which are numbers or range of numbers, but to ignore white spaces. 我有下一个问题,有带有列数据的表(类型-nvarchar),此列可以包含任何字符,我只需要选择数字或数字范围内的数据,而忽略空格。 For example: 例如:

declare @tmp table (data nvarchar(192), Result nvarchar(192));

insert into @tmp SELECT '123', '<- valid';
insert into @tmp SELECT ' 123 ', '<- valid';
insert into @tmp SELECT '123-123', '<- valid';
insert into @tmp SELECT ' 123 - 123 ', '<- valid';
insert into @tmp SELECT '123jmj', '<- invalid';
insert into @tmp SELECT '123,5441', '<- invalid';
insert into @tmp SELECT '123,yjyj', '<- invalid';

SELECT * FROM @tmp

The result dataset must contains only valid rows. 结果数据集必须仅包含有效行。 I can try the next 我可以尝试下一个

SELECT * FROM @tmp WHERE data NOT LIKE '%[^0-9]%'

But I got only first row. 但是我只有第一排。

First replace the white spaces with empty string 首先替换white spacesempty string

Next replace the - with . 接下来,将-替换为.

Third use ParseName trick to separate the data. 第三次使用ParseName技巧来分隔数据。

After the separation you can filter the records using NOT LIKE '%[^0-9]%' 分离之后,您可以使用NOT LIKE '%[^0-9]%'过滤记录

SELECT data
FROM   (SELECT *,
               Parsename(Replace(Replace(data, ' ', ''), '-', '.'), 2) st,
               Parsename(Replace(Replace(data, ' ', ''), '-', '.'), 1) ed
        FROM   @tmp) a
WHERE  st NOT LIKE '%[^0-9]%'
        OR ed NOT LIKE '%[^0-9]%' 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM