Conversion Failed Nvarchar to INT - sql

I have two tables called Entry_Data and Data
Entry_Data has three columns:
EntryID DataID DataTypeID
1       50      18
2       49       59
30      28      16
Data has two columns:
DataID Value
50      0x00000000033654
49      Removable
28      E:\Test.txt
The Value column is an nvarchar field.
I have written a left join while attempting to convert all Value fields that start with 0x to an int so that the Hexadecimal value can be converted into a meaningful and human readable value however I get the error:
Conversion failed when converting the nvarchar value
‘0x00000000033654’ to data type int
SELECT TOP 100
Entry_Data.DataTypeID AS DataTypeID,
CAST(Data.Value AS nvarchar(440)) AS Value,
Data.DataID AS DataID
FROM ActivityLog.Entry_Data
LEFT JOIN ActivityLog.Data
ON ActivityLog.Entry_Data.DataID =
CASE
WHEN DataTypeID = 18 AND
Value LIKE '%0x%' THEN CONVERT(nvarchar, CONVERT(int, Value, 1))
ELSE DataTypeID
END
WHERE DataTypeID = 18

In your case expression, you are returning an nvarchar for one situation
THEN CONVERT(nvarchar, CONVERT(int, Value, 1))
and an integer for the second situation
ELSE DataTypeID
You need to correct your join so it always return and int for the join to work.

Related

use cast in SQL case statement

SELECT
CASE
WHEN column1 = 43 THEN CAST('abcde' as varchar(30))
WHEN column1 = 44 THEN CAST('fghij' as varchar(30))
ELSE 'N/A'
END AS value
Is the above case and cast statement correct? I need to convert the int to a varchar. column1 is a value that comes from another table.
Question 2: I have two values coming from two different tables (table1 and table2) and they need to go to the final table data type varchar
value 1 = CONVERT(VARCHAR(10),CAST(c.table1 * 100 AS DECIMAL(5,2))) + ' %' AS value1
value 2 = CONVERT(VARCHAR(10),c.table2,101) AS value2
c.table1 is decimal coming from table1
c.table2 is int coming from table2 and both need to be varchar at the final table
how do I combine both statements so that it can show up in the final table, its not an OR its an AND.
result set:

The conversion of the varchar value overflowed an int column with sql server

The conversion of the varchar value '82332617284' overflowed an int column.
I have data such as
BreakID = 82332617284
Thus I have line of code to pull out the number only, so it looks like the following:
join dst.ExceptionsDST d on f.BreakOwnerId = replace(substring(d.dstbreakid,charindex('=',d.dstbreakid) + 1,99),' ','')
What do I need to do in order to just pull the numbers and do the join without getting this error?
It is definitely something with this part
replace(substring(d.dstbreakid,charindex('=',d.dstbreakid) + 1,99),' ','')
int is too small a datatype for your number. You'll have to get rid of so big numbers, or change the column datatype to bigint.
You can use TRY_CONVERT to avoid this error:
SELECT dstbreakid, TRY_CONVERT(INT, SUBSTRING(d.dstbreakid, CHARINDEX('=', d.dstbreakid) + 1, 99))
FROM (VALUES
('x = 82332617284 '),
('x = 823326172 ')
) d(dstbreakid)
Output:
| dstbreakid | (No column name) |
|-----------------|------------------|
| x = 82332617284 | NULL |
| x = 823326172 | 823326172 |
If f.BreakOwnerId is of datatype int then it cannot contain the value 823326172.
It's clear that your value is bigint. Int datatype can't hold it.
For Example, I'm trying to insert your value #t which is int data type. Will end up with same error
create table #t (id int)
insert into #t values(82332617284)
but this wont error out because it is bigint.
create table #t1 (id bigint)
insert into #t1 values(82332617284)
So if you can change your code like below will help,
join dst.ExceptionsDST d on f.BreakOwnerId = CAST(replace(substring(d.dstbreakid,charindex('=',d.dstbreakid) + 1,99),' ','') as Bigint)

SQL: Conversion failed when converting the nvarchar value 'XXX' to data type int

I am getting 'Conversion failed when converting the nvarchar value 'XXX' to data type int' error for no obvious reason and I don't know how to fix it. The view actually returns the correct data to stored procedure but it is giving me this error. I'm stuck. Anyone please give me some pointers?
SELECT d.Code, a.Agency, a.Agency_job, a.OUCode, a.JobCode, d.OraUser, c.ProfileName
FROM dbo.Agency AS a
LEFT OUTER JOIN dbo.IdM AS d ON REPLACE(STR(a.OUCode, 3), ' ', '0') = d.OrganizationUnitCode AND a.JobCode = d.JobCode
LEFT OUTER JOIN dbo.Profiles AS c ON c.JobCode = a.JobCode AND c.OUCode = a.OUCode
WHERE (d.Code IS NOT NULL)
Column details -
d.Code is nvarchar(32),
d.OraUser is nvarchar(100),
d.OrganizationUnitCode is nvarchar(16),
a.Agency is int,
a.Agency_job is int,
a.OUCode is int,
a.JobCode is int,
c.ProfileName is varchar(100),
c.OUCode is int,
c.JobCode is int.
Does anyone maybe see a potential problem?
It is only normal for the error to happen in your query!
REPLACE(STR(a.OUCode, 3), ' ', '0') is of string type but d.OrganizationUnitCode on the right side of join predicate is an int. So it cannot implicitly do the conversion here, either convert the int field to nvarchar or the other way around. you can try something like this:
cast(REPLACE(STR(a.OUCode, 3), ' ', '0') as int) = d.OrganizationUnitCode
If you have OUCode > 999 in your tables, the STR(a.OUCode, 3) will return *** which when trying to convert to int would give you the error
Conversion failed when converting the varchar value '***' to data type int.
From books online : https://learn.microsoft.com/en-us/sql/t-sql/functions/str-transact-sql?view=sql-server-2017
When the expression exceeds the specified length, the string returns ** for the specified length.
The other issue I can see is :
What is the datatype of JobCode in your IdM Table ?. Try this and see if it returns any results :
SELECT JobCode FROM dbo.IdM WHERE ISNUMERIC(JobCode) = 0
Below is the answer:
SELECT d.Code, a.Agency, a.Agency_job, a.OUCode, a.JobCode, d.OraUser, c.ProfileName
FROM dbo.Agency AS a
LEFT OUTER JOIN dbo.IdM AS d ON CAST(REPLACE(STR(a.OUCode, 3), ' ', '0') AS NVARCHAR(16)) = d.OrganizationUnitCode AND a.JobCode = d.JobCode
LEFT OUTER JOIN dbo.Profiles AS c ON c.JobCode = a.JobCode AND c.OUCode = a.OUCode
WHERE (d.Code IS NOT NULL)
Also choose a correct value while using STR function.

Conversion failed when converting the varchar value 'simple, ' to data type int

I am struggling for a few days with this issue and I can't figure out how can I fix it.
I would like to group by my table on values 1,2,3,4,5 so I have created a temporary table with this values.
Now I have to INNER JOIN this table with other tables on a.value = #myTempTable.num.
BUT a.value is ntext so I need to CONVERT it what I actually did, but I am getting an error:
Conversion failed when converting the varchar value 'simple, ' to data
type int. (on line 7)
Create table #myTempTable
(
num int
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)
SELECT a.name, CONVERT(INT, CONVERT(VARCHAR(12), a.value)) AS value, COUNT(*) AS pocet
FROM
(SELECT item.name, value.value
FROM mdl_feedback AS feedback
INNER JOIN mdl_feedback_item AS item
ON feedback.id = item.feedback
INNER JOIN mdl_feedback_value AS value
ON item.id = value.item
WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
) AS a
INNER JOIN #myTempTable
on CONVERT(INT, CONVERT(VARCHAR(12), a.value)) = #myTempTable.num
GROUP BY a.name, CONVERT(INT, CONVERT(VARCHAR(12), a.value)) ORDER BY a.name
drop table #myTempTable
I am not getting this error without the last INNER JOIN
INNER JOIN #myTempTable on CONVERT(INT, CONVERT(VARCHAR(12), a.value))
= #myTempTable.num
Could someone help me please?
Thanks.
In order to avoid such error you could use CASE + ISNUMERIC to handle scenarios when you cannot convert to int.
Change
CONVERT(INT, CONVERT(VARCHAR(12), a.value))
To
CONVERT(INT,
CASE
WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value)
ELSE 0 END)
Basically this is saying if you cannot convert me to int assign value of 0 (in my example)
Alternatively you can look at this article about creating a custom function that will check if a.value is number: http://www.tek-tips.com/faqs.cfm?fid=6423
If you are converting a varchar to int make sure you do not have decimal places.
For example, if you are converting a varchar field with value (12345.0) to an integer then you get this conversion error. In my case I had all my fields with .0 as ending so I used the following statement to globally fix the problem.
CONVERT(int, replace(FIELD_NAME,'.0',''))
Given that you're only converting to ints to then perform a comparison, I'd just switch the table definition around to using varchar also:
Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)
and remove all of the attempted CONVERTs from the rest of the query.
SELECT a.name, a.value AS value, COUNT(*) AS pocet
FROM
(SELECT item.name, value.value
FROM mdl_feedback AS feedback
INNER JOIN mdl_feedback_item AS item
ON feedback.id = item.feedback
INNER JOIN mdl_feedback_value AS value
ON item.id = value.item
WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
) AS a
INNER JOIN #myTempTable
on a.value = #myTempTable.num
GROUP BY a.name, a.value ORDER BY a.name

SQL Different column type comparison error

Hi I have a stored procedure which suppose to compare between 2 columns on different tables
Users.ID => int
Trans.ID => nvarchar
Sometimes the value in Trans.ID is not numeric at all, and sometimes it's null, which causes an error while trying to compare
is there a way to try to parse Trans.ID into a number and in case it doesn't succeed to return 0??
I tried NullIf() but it doesn't work when the value inside is not numeric.
Assuming Trans.ID is a varchar(20) field, you can convert the Users.ID field to a varchar, use COALESCE to handle NULL values, and compare as follows:
WHERE CAST(Users.ID AS varchar(20)) = COALESCE(Trans.ID, '')
If using sql server you can do this
CASE WHEN ISNUMERIC(Trans.ID) = 0 then null
else cast(Trans.ID as int) end = Users.ID
you can do something like:
select * from users u
inner join trans t on u.userid = (CASE WHEN ISNUMERIC(t.id) = 1 THEN CONVERT(int, t.id) ELSE 0 END)
hope this helps.
If it is just equality comparison (which I think it is to make sense), I would convert Users.ID to NVARCHAR and then compare with Trans.ID.
IsNumeric() is not always right, e.g. ' - ' and '.' both return 1 for IsNumeric, but will fail your query.
This function (Adapted from here)
create function dbo.GetNumeric(#x varchar(10)) returns float as
begin
return
case
when #x is null or #x = '' then null -- blanks
when #x like '%[^0-9e.+-]%' then null -- non valid char found
when #x like 'e%' or #x like '%e%[e.]%' then null -- e cannot be first, and cannot be followed by e/.
when #x like '%e%_%[+-]%' then null -- nothing must come between e and +/-
when #x='.' or #x like '%.%.%' then null -- no more than one decimal, and not the decimal alone
when #x like '%[^e][+-]%' then null -- no more than one of either +/-, and it must be at the start
when #x like '%[+-]%[+-]%' and not #x like '%[+-]%e[+-]%' then null
else convert(float,#x)
end
end
Your query (involving inequality)
where users.id >= case when IsNull(dbo.GetNumeric(trans.id),0)
And if trans.id does not involve decimal points
where user.id >= case when trans.id not like '%[^0-9]%' and trans.id >''
then trans.id end
Of course, if it's a simple equality, just cast the int to a varchar
where right(users.id,10) = trans.id