Reputation: 299
i have items table which is having Size as follows:
1sq.mm.
1.5sq.mm.
0.5sq.mm.
2.5sq.mm.
0.75sq.mm.
4sq.mm.
20mm
25mm
20mtr
75mm x 50mm
100mm x 50mm
100mm x 100mm
75mm x 75mm
i wanted to display it has
0.5sq.mm.
0.75sq.mm.
1.5sq.mm.
2.5sq.mm.
4sq.mm.
20mm
20mtr
25mm
75mm x 50mm
75mm x 75mm
100mm x 50mm
100mm x 100mm
i tried the following sql query but am getting error
'Conversion failed when converting the varchar value '1 sq.mm.' to data type int.'
SQL query:
select * from Items
order by CAST(SUBSTRING(Sizes, PATINDEX('%[0-9]%', Sizes), LEN(Sizes)) AS INT)
Upvotes: 0
Views: 261
Reputation: 82524
Try this:
SELECT Sizes
FROM Items
ORDER BY CAST(LEFT(Sizes, PATINDEX('%[a-z]%', Sizes)-1) as numeric(9, 2))
that's assuming your data will always be number followed by at least one alphabetic char.
Upvotes: 1
Reputation: 10915
Just a suggestion - not an answer:
I would reconsider to design the table differently - if possible. At the moment, you are sorting a column with two different types of information: length (mm) and area (sq.mm) which makes little sense.
Maybe you would rather have a data structure like this:
CREATE TABLE MyTable(
length decimal(5,2),
width decimal(5,2),
area decimal(10,2),
unit varchar(10)
)
Needless to say that with this design it would be very simple to sort.
Upvotes: 0
Reputation: 1155
CREATE FUNCTION udf_GetNumeric
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
RETURN ISNULL(@strAlphaNumeric,0)
END
GO
SELECT dbo.udf_GetNumeric('sada322sds232132132');
drop function udf_GetNumeric;
Result
322232132132
CAST(dbo.udf_GetNumeric(Sizes) AS INT)
Upvotes: 1
Reputation: 15061
Use REPLACE
in the ORDER BY
SELECT Sizes
FROM Items
ORDER BY CAST(REPLACE(Sizes,'sq.mm.','') as NUMERIC(9,2))
OUTPUT:
Sizes
0.5sq.mm.
0.75sq.mm.
1sq.mm.
1.5sq.mm.
2.5sq.mm.
4sq.mm.
SQL Fiddle: http://sqlfiddle.com/#!3/ad91f/3/0
Upvotes: 4