How to retrieve rows which contain exactly 4 numbers in Microsoft SQL Server?
This query returns string more than 4 numbers
SELECT *
FROM table
WHERE Name LIKE '%[0-9][0-9][0-9][0-9]%';
How to retrieve rows which contain exactly 4 numbers in Microsoft SQL Server?
This query returns string more than 4 numbers
SELECT *
FROM table
WHERE Name LIKE '%[0-9][0-9][0-9][0-9]%';
SQL Server is purposely bad at string manipulation, probably to promote Microsoft's client side tooling, like C# or Reporting Server. See for example this question from 2009. So the sane solution involves creating a CLR UDF.
But you can still do it in T-SQL with a lot of trickery. For example, you could create a user-defined function that removes all numbers from a string:
create function dbo.StripNumbers(@str nvarchar(max))
returns nvarchar(max)
as begin
declare @i int = patindex('%[0-9]%', @str)
while @i > 0
begin
set @str = stuff(@str, @i, 1, '')
set @i = patindex('%[0-9]%', @str)
end
return @str
end
Then you can filter for strings that are 4 characters shorter when stripped:
select *
from YourTable
where len(dbo.StripNumbers(txt)) = len(txt) - 4
You could use wildcards for this:
select *
from Table
where Name like '%[0-9]%[0-9]%[0-9]%[0-9]%'
and Name not like '%[0-9]%[0-9]%[0-9]%[0-9]%[0-9]%'