有没有办法在select语句中根据它是否为数字来转换nvarchar字段。我目前有这个代码,但由于某种原因,它试图转换其中一个非数字值。
SELECT id,
CASE WHEN ISNUMERIC(field) = 1 THEN CAST(field AS INT) ELSE CAST(field AS NVARCHAR(10)) END AS [fieldName]
FROM table1
答案 0 :(得分:0)
如果用零填充数值的左边,它会正确排序吗,如下所示?
DECLARE @Table1 TABLE (Field NVARCHAR(10))
INSERT INTO @Table1 (Field) VALUES (1)
INSERT INTO @Table1 (Field) VALUES (10)
INSERT INTO @Table1 (Field) VALUES (100)
INSERT INTO @Table1 (Field) VALUES (2)
INSERT INTO @Table1 (Field) VALUES ('abv')
SELECT
Field,
CASE
WHEN ISNUMERIC(Field) = 1
THEN RIGHT('000000000' + Field,10)
ELSE Field
END AS SortField
FROM @Table1
ORDER BY SortField DESC
SELECT
Field,
CASE
WHEN ISNUMERIC(Field) = 1
THEN RIGHT('000000000' + Field,10)
ELSE Field
END AS SortField
FROM @Table1
ORDER BY SortField ASC