Conversion failed when converting the nvarchar to int - sql-server

I have a field which is varchar and contains numbers and dates as strings. I want to update all numbers in this field that is greater than 720. I have attempted firstly to do a select but I get this error:
Conversion failed when converting the nvarchar value '16:00' to data type int.
This is my query:
select id, case(isnumeric([other08])) when 1 then [other08] else 0 end
from CER where sourcecode like 'ANE%' --and other08 > 720
It fails when I uncomment the last part.
I am trying to get all numerics greater than 720, but I can't do the comaprison. It also fails when casting and converting.
Thanks all for any help

You also need to perform the checks and conversion in the WHERE clause:
SELECT
id,
CASE WHEN isnumeric([other08]) = 1 THEN CAST([other08] AS INT) ELSE 0 END
FROM CER
WHERE sourcecode LIKE 'ANE%'
AND CASE WHEN isnumeric([other08]) = 1 THEN CAST([other08] AS INT) ELSE 0 END > 720

You need to use IsNumeric in your where clause, to avoid trying to compare strings to the number 720. Eg:
select id, case(isnumeric([other08])) when 1 then [other08] else 0 end
from CER
where sourcecode like 'ANE%' and ISNUMERIC(other08) = 1 and other08 > 720
EDIT
As #Abs pointed out, the above approach won't work. We can use a CTE to compute a reliable field to filter on, however:
WITH Data AS (
select id
, case WHEN isnumeric([other08]) THEN CAST([other08] AS int) else 0 end AS FilteredOther08
, CER.*
from CER
where sourcecode like 'ANE%'
)
SELECT *
FROM Data
WHERE [FilteredOther08] > 720

Related

If the sum of the whole column is zero, then change the value of each row in SQL Server

I have a column named Percentage from a temporary table info, which if the sum of the whole column is zero, I want to change the value of each row to 0.5, and if the statement is false just leave it that way.
I have tried to do the following:
select case when Percentage = 0 then replace(Percentage, 0,0.5) end from ##info
I know the above will change the fields whenever they are 0 regardless of the sum of the whole column, and if I do:
select case when sum(Percentage) = 0 then replace(Percentage, 0,0.5) end from ##info
it would throw an error.
Another thing is that I want to replace the temporary table with that column and the above code would only give me the actual column without replacing the original column.
Any suggestions are appreciated
If you want to select it:
SELECT
CASE
WHEN (SELECT SUM(Percentage) FROM ##info) = 0 THEN .5
ELSE Percentage
END
FROM ##info
If you want to update the values in the table:
UPDATE ##info
SET Percentage = .5
WHERE (SELECT SUM(Percentage) FROM ##info) = 0
Please find below answer.
declare #v_val numeric(12,2), #v_new_val numeric(12,2)
set #v_val = 0.00
set #v_new_val = 100
select case when #v_val ='0.00' then #v_new_val else #v_val end

Error converting varchar to bigint in very peculiar situation

My intent is to retrieve all CLIENT_CODE converted to BigInt, to compare with a value passed as a parameter in the where clause from a 400 lines sql query. When execute the code below, I get the following error message:
message error 8114 from sql server: "Error converting varchar to
bigint".
Test Code:
select CASE when (len (CLIENT_CODE) > 2 and isNumeric(CLIENT_CODE) = 1)
then (CAST(SUBSTRING(TAB.CLIENT_CODE, 1, LEN(TAB.CLIENT_CODE)-1) AS BIGINT))
else CLIENT_CODE end from TABLE TAB
Code Nested:
--HUGE_SQL...
AND ((CASE when (len (CLIENT_CODE) > 2 and isNumeric(CLIENT_CODE) = 1)
then (CAST(SUBSTRING(TAB.CLIENT_CODE, 1, LEN(TAB.CLIENT_CODE)-1) AS BIGINT))
else CLIENT_CODE end) = #MyClient_Code)
--... HUGE_SQL
Our CLIENT_CODE is varchar(20), some have 0 characters, and some have letters, but almost every record is a number.
In my understanding, the case must be evaluated first, but it don't appear to be the case.
When i put the isNumeric(CLIENT_CODE) = 1 in the where clause, in test code, it works. My problem is that i can't do it in this particular case, because the fact it is already nested in the where clause from a huge sql query, and adding the isNumeric(CLIENT_CODE) = 1 there doesn't work, because it has a lot of other conditions.
Which is the best way to retrieve this data? Can someone figure it out how to do it?
(It will be very helpfull some kind of explanation of how is treated the functions vs case vs where)
Your Case expression Returns BIGINT in one case and else it return VARCHAR data type .
For Case expression, in each case the returned data type must be same.
Also instead of using ISNUMERIC() use following
select CASE
when (len (CLIENT_CODE) > 2 and CLIENT_CODE NOT LIKE '%[^0-9]%')
then (CAST(SUBSTRING(TAB.CLIENT_CODE, 1, LEN(TAB.CLIENT_CODE)-1) AS BIGINT))
end
from TABLE TAB
ISNUMERIC() returns true for values like 123a1 , 346g2 it considers it as raise to power stuff, therefore use NOT LIKE '%[^0-9]%' to get strings where only actual numeric values are present.

Can I write a conditional AND to test for "ISNUMERIC" and then CAST a string to an int in T-SQL?

I thought (hoped) this would work but it doesn't, it evaluates both sided of the AND statement even if the left side is going to be false:
SELECT PropertyNumber
FROM Properties
WHERE PropertyNumber = '203a'
AND
(
NOT PropertyNumber LIKE '[^0-9]' AND CONVERT(INT,PropertyNumber) > 0
)
So I get:
Conversion failed when converting the nvarchar value '203a' to data type int.
Is there anyway to do conditional AND or any other way to solve this problem?
You can do this in two steps:
SELECT
OtherField, CAST(PropertyNumber AS INT) AS PropertyNumber
FROM
(SELECT OtherField, PropertyNumber FROM Properties WHERE ISNUMERIC(PropertyNumber) = 1) AS X
This will discard records with non-numeric property numbers. If you want to keep them...
SELECT
P.OtherField, P.PropertyNumber AS PropertyNumberAsText, CAST(X.PropertyNumber AS INT) AS PropertyNumberAsInt
FROM
Properties AS P
LEFT JOIN (SELECT DISTINCT PropertyNumber FROM Properties WHERE ISNUMERIC(PropertyNumber) = 1) AS X ON P.PropertyNumber = X.PropertyNumber
Because ISNUMERIC() approves of some values which cannot be cast to INT, I tend to use something like this:
CASE WHEN Field IN ('-', '.') THEN NULL
WHEN Field LIKE '%,%' THEN NULL
WHEN ISNUMERIC(Field) = 1 THEN CAST(Field AS INT) END
Note that this will reject values like "1,234", which is a valid integer in some regions. Code to identify and handle all possible formats for numeric values is a separate question, and has probably been asked on SO before.
try this:
SELECT PropertyNumber
FROM #Temp
WHERE PropertyNumber = '203a'
AND
(
case When IsNumeric('-' + PropertyNumber + 'e0') = 1
Then Convert(Int, PropertyNumber)
Else NULL
End > 0
)
The trick here is to use the knowledge that IsNumeric will return 1 only under certain conditions. By putting a '-' sign in front of your data, you are effectively making sure that property numbers are positive. By putting 'e0' after the column name, you are preventing floating point values.

'Converting varchar to data type numeric' error after successful conversion to decimal(18,2)

I have a temporary table I'm using for parsing, #rp.
#rp contains an nvarchar(max) column, #rp.col8, which holds positive and negative numbers to two decimal places of precision e.g. `1234.26'.
I'm able to run the following query and get out a set of converted values out:
select * from
(
select CONVERT(decimal(18,2),rp.col8) as PARSEAMT
from #rp
where
--#rp filtering criteria
)q
However, when I try to query for PARSEAMT = 0 in the following manner, I get the standard '8114, Error converting data type varchar to numeric.':
select * from
(
select CONVERT(decimal(18,2),col8) as PARSEAMT
from #rp
where
--#rp filtering criteria
)q
where q.PARSEAMT = 0
Without that where clause, the query runs fine and generates the expected values.
I've also tried other clauses like where q.PARSEAMT = 0.00 and where q.PARSEAMT = convert(decimal(18,2),0).
What am I doing wrong in my comparison?
I was going to suggest you select PARSEAMT into another temp-table/table-variable but I can see you've already done that from your comments.
Out of interest what does the following yield?
select
col8
from
#rp
where
-- ISNUMERIC returns 1 when the input expression evaluates to a valid
-- numeric data type; otherwise it returns 0. Valid numeric data types
-- include the following:
isnumeric(col8) <> 1

Natural sort for SQL Server?

I have a column that is typically only numbers (sometimes it's letters, but that's not important).
How can I make it natural sort?
Currently sorts like this: {1,10,11,12,2,3,4,5,6,7,8,9}
I want it to sort like this: {1,2,3,4,5,6,7,8,9,10,11,12}
IsNumeric is "broken", ISNUMERIC(CHAR(13)) returns 1 and CAST will fail.
Use ISNUMERIC(textval + 'e0'). Final code:
ORDER BY
PropertyName,
CASE ISNUMERIC(MixedField + 'e0') WHEN 1 THEN 0 ELSE 1 END, -- letters after numbers
CASE ISNUMERIC(MixedField + 'e0') WHEN 1 THEN CAST(MixedField AS INT) ELSE 0 END,
MixedField
You can mix order parameters...
Cast it. Also, don't forget to use IsNumeric to make sure you only get the numbers back (if they include letters it IS important ;).
SELECT textval FROM tablename
WHERE IsNumeric(textval) = 1
ORDER BY CAST(textval as int)
Also, cast to the datatype that will hold the largest value.
If you need the non-numbers in the result set too then just append a UNION query where IsNumeric = 0 (order by whatever you want) either before or after.
Have you tied using:
'OrderBy ColumnName Asc'
at the end of your query.

Resources