我有物品表,其大小如下:
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
我想显示它
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
我尝试了以下sql查询但收到错误
'Conversion failed when converting the varchar value '1 sq.mm.' to data type int.'
SQL查询:
select * from Items
order by CAST(SUBSTRING(Sizes, PATINDEX('%[0-9]%', Sizes), LEN(Sizes)) AS INT)
答案 0 :(得分:4)
在REPLACE
ORDER BY
SELECT Sizes
FROM Items
ORDER BY CAST(REPLACE(Sizes,'sq.mm.','') as NUMERIC(9,2))
输出:
Sizes
0.5sq.mm.
0.75sq.mm.
1sq.mm.
1.5sq.mm.
2.5sq.mm.
4sq.mm.
答案 1 :(得分:1)
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)
答案 2 :(得分:1)
答案 3 :(得分:0)
只是建议 - 不是答案:
我会重新考虑以不同方式设计表格 - 如果可能的话。 目前,您正在使用两种不同类型的信息对列进行排序:长度(mm)和面积(sq.mm),这没什么意义。
也许你宁愿拥有这样的数据结构:
CREATE TABLE MyTable(
length decimal(5,2),
width decimal(5,2),
area decimal(10,2),
unit varchar(10)
)
毋庸置疑,通过这种设计,排序非常简单。