Reputation: 2593
I have a column that contains characters and numbers
12
13
14
19K/YR
22
So the column type is varchar. But then I'm also doing some computations with this column, so I'm trying to convert the data to float if it is numeric.
This gives me an error though:
SELECT CASE ISNUMERIC(QTY)
WHEN 1 THEN CAST(QTY AS float)
ELSE QTY
END AS test
Upvotes: 15
Views: 128015
Reputation: 441
I found this very annoying bug while converting EmployeeID values with ISNUMERIC:
SELECT DISTINCT [EmployeeID],
ISNUMERIC(ISNULL([EmployeeID], '')) AS [IsNumericResult],
CASE WHEN COALESCE(NULLIF(tmpImport.[EmployeeID], ''), 'Z')
LIKE '%[^0-9]%' THEN 'NonNumeric' ELSE 'Numeric'
END AS [IsDigitsResult]
FROM [MyTable]
This returns:
EmployeeID IsNumericResult MyCustomResult ---------- --------------- -------------- 0 NonNumeric 00000000c 0 NonNumeric 00D026858 1 NonNumeric (3 row(s) affected)
Hope this helps!
Upvotes: 2
Reputation: 128
-- TRY THIS --
select name= case when isnumeric(empname)= 1 then 'numeric' else 'notmumeric' end from [Employees]
But conversion is quit impossible
select empname=
case
when isnumeric(empname)= 1 then empname
else 'notmumeric'
end
from [Employees]
Upvotes: -1
Reputation: 432311
..extending Mikaels' answers
SELECT
CASE WHEN ISNUMERIC(QTY + 'e0') = 1 THEN CAST(QTY AS float) ELSE null END AS MyFloat
CASE WHEN ISNUMERIC(QTY + 'e0') = 0 THEN QTY ELSE null END AS MyVarchar
FROM
...
e0
fixes some ISNUMERIC issues (such as +
-
.
and empty string being accepted)Upvotes: 13
Reputation: 138960
You can't cast to float and keep the string in the same column. You can do like this to get null when isnumeric returns 0.
SELECT CASE ISNUMERIC(QTY) WHEN 1 THEN CAST(QTY AS float) ELSE null END
Upvotes: 33