SQL update query fails to convert nvarchar to integer

532 views Asked by At

The following query should return records that consist of 3 or 4 digits that are converted from nvarchar to integer and are lower than 1200. Instead of a desired result, an error returns stating: Conversion failed when converting the nvarchar value '' to data type int.

UPDATE cvUpd
SET cvUpd.visible = case when CONVERT(int, cvFrom.ConfigText) < 1200 then 0 else 1 end
FROM ConfigValue cvUpd
INNER JOIN OptionRestriction r ON cvUpd.ConfigurationID=67061
   AND cvUpd.FeatureID = r.Feature_ID_2
   AND cvUpd.OptionValue= r.OptionValue_2
INNER JOIN ConfigValue cvFrom ON cvFrom.FeatureID =r.Feature_ID_1  
   AND cvFrom.ConfigurationID = cvUpd.ConfigurationID 
   AND cvFrom.OptionValue=r.OptionValue_1 
   AND cvFrom.ConfigText=r.value
   AND cvFrom.ConfigText NOT LIKE '%[^0-9]%' 
   AND (LEN(cvFrom.ConfigText) = 3 or LEN(cvFrom.ConfigText) = 4)

I also tried to run a select query, but this query resulted in the same error:

SELECT CONVERT(int, cvFrom.ConfigText)
FROM ConfigValue cvUpd
INNER JOIN OptionRestriction r ON cvUpd.ConfigurationID=67061
   AND cvUpd.FeatureID = r.Feature_ID_2
   AND cvUpd.OptionValue= r.OptionValue_2
INNER JOIN ConfigValue cvFrom ON cvFrom.FeatureID =r.Feature_ID_1  
   AND cvFrom.ConfigurationID = cvUpd.ConfigurationID 
   AND cvFrom.OptionValue=r.OptionValue_1 
   AND cvFrom.ConfigText=r.value
   AND cvFrom.ConfigText NOT LIKE '%[^0-9]%' 
   AND (LEN(cvFrom.ConfigText) = 3 or LEN(cvFrom.ConfigText) = 4)

UPDATE

It appears that I get the same error even without using convert:

SELECT cvFrom.ConfigText
FROM ConfigValue cvUpd
INNER JOIN OptionRestriction r ON cvUpd.ConfigurationID=67061
   AND cvUpd.FeatureID = r.Feature_ID_2
   AND cvUpd.OptionValue= r.OptionValue_2
INNER JOIN ConfigValue cvFrom ON cvFrom.FeatureID =r.Feature_ID_1  
   AND cvFrom.ConfigurationID = cvUpd.ConfigurationID 
   AND cvFrom.OptionValue=r.OptionValue_1 
   AND cvFrom.ConfigText=r.value
   AND cvFrom.ConfigText NOT LIKE '%[^0-9]%' 
   AND (LEN(cvFrom.ConfigText) = 3 or LEN(cvFrom.ConfigText) = 4)
1

There are 1 answers

0
user2237168 On

The problem was that r.value was an integer that was joined with the nvarchar "cvFrom.ConfigText". I therefore needed to edit AND cvFrom.ConfigText=r.value to AND cvFrom.ConfigText=CONVERT(nvarchar(max), r.value).