Reputation: 947
I'm trying to filter data from my table using regex pattern in SQL Management Studio 2008 R2.
My table "Asset" contain the column "Asset_n" which contains the asset names. The goal is to be able to filter five types of names only:
12345
123456
12345a
or 12345ab
123456a
or 123456ab
Here is my query:
SELECT * FROM Asset WHERE asset_n LIKE [\d{5,6}\w{1,2}]
The query return nothing... I have used the same regex pattern in PowerShell and it's working perfectly. SQL is something new for me so I don't realy know how to build my regex pattern for SQL query's.
Thanks in advance for your help.
Upvotes: 0
Views: 93
Reputation: 35790
Try this:
select * from Asset
where left(asset_n, 5) not like '%[^0-9]%' and
(SUBSTRING(asset_n, 6, 4) like '[0-9][a-z][a-z]' or
SUBSTRING(asset_n, 6, 4) like '[0-9][a-z]' or
SUBSTRING(asset_n, 6, 4) like '[0-9]' or
SUBSTRING(asset_n, 6, 4) = '')
Why 4? Because of you have maximum length of 8 charachters and you want to filter those whose length are greater.
Upvotes: 0
Reputation: 1720
SQL Server doesn't support regex in LIKE argument, however you could do what you want using the following query:
SELECT * FROM Asset WHERE
asset_n LIKE '[0-9][0-9][0-9][0-9][0-9]'
OR asset_n LIKE '[0-9][0-9][0-9][0-9][0-9][0-9]'
OR asset_n like '[0-9][0-9][0-9][0-9][0-9][a-z]' OR asset_n like '[0-9][0-9][0-9][0-9][0-9][a-z][a-z]'
OR asset_n like '[0-9][0-9][0-9][0-9][0-9][0-9][a-z]' OR asset_n like '[0-9][0-9][0-9][0-9][0-9][0-9][a-z][a-z]'
Upvotes: 1