Question

How can i select a range of items from a VARCHAR type column in sql server?

I want to make something like:

SELECT TE.DESC 
FROM PRODUCT P, ETYPE TE WHERE ( P.IDTYPE = TE.IDTYPE )
AND P.NUMBER BETWEEN '619' AND '623'

The 'P.NUMBER' column can contain numbers and letters together like 'abc123', then sql can't select correctly what i want.

There's some way to do it?

Thanks

Was it helpful?

Solution

First, you need to create a function which will strip all non-numeric characters from your NUMBER and return a float (or int), like so:

create function dbo.RemoveAlpha(@str varchar(1000))
returns float
AS
begin
    while patindex('%[^0-9]%', @str) > 0
    begin
        set @strText = stuff(@str, patindex('%[^0-9]%', @str), 1, '')
    end
    return convert(float, @str)
end

Then your can rewrite your query like so:

SELECT TE.DESC 
FROM PRODUCT P, ETYPE TE 
WHERE ( P.IDTYPE = TE.IDTYPE )
AND dbo.RemoveAlpha(P.NUMBER) BETWEEN 619 AND 623

OTHER TIPS

You can get only numbers using this double CASE

SELECT TE.DESC 
FROM PRODUCT P, ETYPE TE WHERE ( P.IDTYPE = TE.IDTYPE )
WHERE 1 = CASE ISNUMERIC(P.NUMBER)
    WHEN 1 THEN
         CASE WHEN CAST(P.NUMBER AS INT) BETWEEN 619 AND 623 THEN 1 ELSE 0 END 
    ELSE 0
END
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top