0

I have the following table:

create table #tbl
(
    PartNumber varchar(20)
)

insert into #tbl values ('003A-I00-1')
insert into #tbl values ('003A-INT-1')
insert into #tbl values ('003A-I1')
insert into #tbl values ('003A-I2')
insert into #tbl values ('003A-I3')

I need to select the highest PartNumber where PartNumber is equal to 003A-I followed only by a number (or numbers). In other words, I need 003A-I3.

What I've tried:

select top 1 partnumber
from #tbl
where partnumber like '003A-I%' + '%[0-9]'
order by partnumber desc

But it doesn't work. It returns 003A-INT-1. I need 003A-I3.

I'm using MS SQL Server 2005.

2 Answers 2

2
select top 1 partnumber
from tbl
where partnumber like '003A-I[0-9]%'
order by partnumber desc

SQLFiddle

Update (in response to @Nicarus's comment:

SELECT top 1 partnumber
FROM tbl
WHERE partnumber LIKE '003A-I[0-9]%'
ORDER BY convert(varbinary(200), partnumber) DESC
Sign up to request clarification or add additional context in comments.

1 Comment

If you have a different collation set, you could get different results because you are ordering by text
-1

If you want to get the numeric values, you can use the ISNUMERIC() function of the SQL The code will be:

select * from #tbl
where isnumeric(replace(partnumber, '003A-I', '')) = 1
order by partnumber desc

REVISE:

ISNUMERIC() function returns Boolean value either true or false (1 or 0). REPLACE() function replaces a certain pattern in an expression or string

For more information:

http://technet.microsoft.com/en-us/library/ms186862.aspx

http://technet.microsoft.com/en-us/library/ms186272.aspx

UPDATE (2): You can use the following if you don't want to match a specific word, but as long as you know the text size which would be replaced

select top 1 * from #tbl
where isnumeric(substring(partnumber, 7, LEN(partnumber))) = 1
order by partnumber desc

The link on the SQLFiddle

4 Comments

Will match 103A-I (for example).
If you're talking about the REPLACE() function, yes it can easily math that or other text. Or a generic solution if you know the size of the text before the Number you can use the SUBSTRING() function. For an example SUBSTRING(partnumber, 0, 5) and use it inside the ISNUMERIC() function
alos returns all matches...not just Max
@MitchWheat You can easily select top 1, since you are order by partnumber desc. If using the SUBSTRING() function, the full code will be as pasted in my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.