Conversion failed when converting the nvarchar value 'AAAR78509883' to data type int - sql

I have a nvarchar column in one of my tables that I have imported from Access. I am trying to change to an int. To move to a new table.
The original query:
insert into members_exams_answer
select
ua.members_exams_id, ua.exams_questions_id,
ua.members_exams_answers_value, ua.members_exams_answers_timestamp
from
members_exams as me
full join
UserAnswers1 as ua on me.members_exams_username = ua.members_exams_id
full join
exams_questions as eq on eq.exams_questions_id = ua.exams_questions_id
This throws an error:
Conversion failed when converting the nvarchar value 'AAAR78509883' to data type int.
I have tired:
select convert (int, UserAnswers1.members_exams_id)
from UserAnswers1
and
select cast(members_exams_id as integer) int_members_exams_id
from UserAnswers1
and
select cast (members_exams_id as int)
from UserAnswers1
All result in the same error
Conversion failed when converting the nvarchar value 'AAAR78509883' to data type int.

Clearly you are trying to convert data that is alphanumeric to an int and that cannot be done.
Looking at your data why are you insisting on converting it to an int when it cannot be an int? Why not just process it as an nvarchar?

Your problem could be systemic where all data has a leading alpha characters that you need to strip out (and hopefully the same number of alpha characters)
In that case use a substring to strip off the alphas (this assumes the name number of alphabetic characters in each record). Or use a varchar or nvarchar field instead of an int. If the number of leading characters varies or if they can be leading or trailing or some other combination, it will much more complex to fix than we can probably describe on the Internet.
The other possibility is that you simply have some bad data. In which case identify the records which are not numeric and fix them or null the value out if they cannot be fixed. This happens frequently when you have stored the data in an incorrect datatype.

Related

What is a type of my value 675763582022462206:57 in sql creating data table query?

I am creating a table with several columns in sql:
CREATE TABLE.....
and one of them is going to have values like this: 675763582022462206:57. As you see it has : in it. So what is a type of it? Is it UInt16 or String?
It must be varchar or nvarchar in this case. The database doesn't recognize ":" as a part of a number, unless you say to Windows in advanced region settings that this is your decimal point. If you can store 57 (after ":") in a different column, then you can save the number before ":" as a bigint if you wish
This value can't be stored in a numeric type due to the colon (:), so you'll have to use one of the character types - i.e., a sufficiently long char or varchar.

Search with inequalities on string property

We are using NHibernate over SQL Server and SQLite.
The database stores records in rows rather than columns -- each row having Path|Value as columns. Path and Value are both string properties.
For certain values of Path we would like to query for inequalities -- greater-than, less-than, etc.
The trouble we are having is that because the properties are strings, the inequalities are using string comparisons -- for example, searching for Value >= 18 returns rows where Value = 5. Unfortunately we are having trouble working around this.
1) This restriction produces incorrect results (saying 18 < 5):
Restrictions.Ge("Value", item.Value);
2) We tried casting the value to an integer, but this code produces a SqlException from NHibernate -- Error converting data type nvarchar to bigint.
Restrictions.Le(Projections.Cast(NHibernateUtil.Int64, Projections.Property("SearchString")), item.Value)
3) We were looking for a way to pad the property value with zeros (so that we would get 018 > 005), but could not find a way to do this in NHibernate.
Does anyone have any advice?
Thank you in advance!
Assuming that you want to compare on integer value, with IQueryOver:
1) This restriction produces incorrect results (saying 18 < 5):
Restrictions.Ge("Value", item.Value);
Restrictions.Ge
(
Projections.Cast(NHibernateUtil.Int32, Projections.Property<YourEntity>(x => x.YourProperty))
, intValue
)
Convert your datatype accordingly. If your C# datatype (intValue) is already numeric, no need to convert it. If your x.YourProperty is already numeric type, no need to convert it. Adjust above code accordingly.
2) We tried casting the value to an integer, but this code produces a SqlException from NHibernate -- Error converting data type nvarchar to bigint.
Restrictions.Le(Projections.Cast(NHibernateUtil.Int64, Projections.Property("SearchString")), item.Value)
Refer the above and check the datatype of item.Value.

Ms Sql Server Compare Numeric column with string value

In MS SQL Server, what is the difference between:
select * from Person where Id='7'
and
select * from Person where Id=7
The two queries returns the same results.
The Id type is int.
should we not compare int to string?
and when should use one of them?
Always compare with the same data type and avoid implicit conversions.
SELECT 'Not OK!' WHERE 'text' = 1
-- Result: Conversion failed when converting the varchar value 'text' to data type int.
As stated by the data type precedence, when there is a mismatch of the data types, the SQL engine will (in most cases) try to convert the most complex type to the simplest, so comparisons are faster. In this case (VARCHAR vs. INT), it will always convert the string type to int.
Also, when coding SQL that has implicit conversions with joins and other operations, it's most likely to generate a different execution plan that the one it would with an explicit conversion.
If you have to compare different types, remember to explicitly cast them, not just for the reason mentioned before but it also says to the next developer that the columns or expressions differ in data type.
SELECT 'OK!' WHERE 'text' = CONVERT(VARCHAR(10), 1)
With some data type you might find unwanted behaviour if you leave implicit conversions.
DECLARE #BitValue1 BIT = NULL
DECLARE #BitValue2 BIT = 1
SELECT
'Oops!'
WHERE
ISNULL(#BitValue1, -999) = ISNULL(#BitValue2, -999)
-- Result: Oops! (-999 is being converted to bit, which is 1)

Operand data type nchar is invalid for avg operator

I have a table that saves the size of file in the database when the user uploads it. I want to get the average value of all the size that the user uploaded.
I have the following column as example that shows the size in Mb's
|Size|
|1.20|
|0.25|
|0.50|
The result that I want as average is something like this
|Size|
|0.65|
When I'm trying to get the average I get this error
Msg 8117, Level 16, State 1, Line 15 Operand data type nchar is
invalid for avg operator.
EDIT
I have changed the column type to nvchar and get this error message when I'm converting it to int
Conversion failed when converting the nvarchar value '0,24' to data
type int.
When I tried it with a decimal I get this error message
Msg 8114, Level 16, State 5, Line 11
Error converting data type nvarchar to numeric.
What can I do to fix this problem.
The error shows you have 0,24 as a number in Swiss or German format.
This is different to 0.24 in British or US format.
So if the datatype was correct as decimal or float, 0,24 would not be allowed because SQL Server does not really deal with continental number formats. See SQL server with german regional settings for more
Then, neither is integer either of course so the int conversion fails.
So, fix the column datatype and the data to fix the error. And you can also avoid nasty client number to string conversions like 24E-2 which is only recognised as float.
And what if you have thousand separators too with mixed format? Imagine this dataset
123.456,79
234,567.89
34E5
0,24
0.24
2.3E-1
Fixing the data will require some LIKE searches. At least these to fix each format one by one.
LIKE '%,%.%'
LIKE '%.%,%'
LIKE '%,%'
LIKE '%E%'
0.24 won't convert to an int as it has decimal part.
You need to do CAST([size] as DECIMAL(9,2)) or some such...
Although we could really do with seeing your code :)
To use this CAST as part of an aggregate...
SELECT [database], AVG(CAST([size] as DECIMAL(9,2))) AS [Average of Size]
FROM table
GROUP BY [database]
Of course I don't know what your table or query actually is...
As others have said - if you are are going to be taking the average anyway then you will be better off not converting the number to an NVARCHAR or VARCHAR in the first place and working with the plain numeric fields.
As gbn notes this is 0,24 continental format so...
SELECT [database], AVG(CAST(REPLACE([size],',','.') as DECIMAL(9,2))) AS [Average of Size]
FROM table
GROUP BY [database]

sql convert error on view tables

SELECT logicalTime, traceValue, unitType, entName
FROM vwSimProjAgentTrace
WHERE valueType = 10
AND agentName ='AtisMesafesi'
AND ( entName = 'Hawk-1')
AND simName IN ('TipSenaryo1_0')
AND logicalTime IN (
SELECT logicalTime
FROM vwSimProjAgentTrace
WHERE valueType = 10 AND agentName ='AtisIrtifasi'
AND ( entName = 'Hawk-1')
AND simName IN ('TipSenaryo1_0')
AND CONVERT(FLOAT , traceValue) > 123
) ORDER BY simName, logicalTime
This is my sql command and table is a view table...
each time i put "convert(float...) part " i get
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.
this error...
One (or more) of the rows has data in the traceValue field that cannot be converted to a float.
Make sure you've used the right combination of dots and commas to signal floating point values, as well as making sure you don't have pure invalid data (text for instance) in that field.
You can try this SQL to find the invalid rows, but there might be cases it won't handle:
SELECT * FROM vwSimProjAgentTrace WHERE NOT ISNUMERIC(traceValue)
You can find the documentation of ISNUMERIC here.
If you look in BoL (books online) at the convert command, you see that a nvarchar conversion to float is an implicit conversion. This means that only "float"-able values can be converted into a float. So, every numeric value (that is within the float range) can be converted. A non-numeric value can not be converted, which is quite logical.
Probably you have some non numeric values in your column. You might see them when you run your query without the convert. Look for something like comma vs dot. In a test scenario a comma instead of a dot gave me some problems.
For an example of isnumeric, look at this sqlfiddle