I have searched both this great forum and googled around but unable to resolve this.
We have two tables (and trust me I have nothing to do with these tables). Both tables have a column called eventId
.
However, in one table, data type for eventId
is float
and in the other table, it is nvarchar
.
We are selecting from table1
where eventI
is defined as float
and saving that Id into table2
where eventId
is defined as nvarchar(50)
.
As a result of descrepancy in data types, we are getting error converting datatype nvarchar
to float
.
Without fooling around with the database, I would like to cast the eventId
to get rid of this error.
Any ideas what I am doing wrong with the code below?
SELECT
CAST(CAST(a.event_id AS NVARCHAR(50)) AS FLOAT) event_id_vre,
3条答案
按热度按时间h4cxqtbf1#
The problem is most likely because some of the rows have
event_id
that is empty. There are two ways to go about solving this:float
tonvarchar
, rather than the other way around - This conversion will always succeed. The only problem here is if the textual representations differ - say, the table withfloat
-as-nvarchar
uses fewer decimal digits, orThe second solution would look like this:
1cklez4t2#
I also received the message "Error converting data type nvarchar to float". This was from a query in SQL Server Management Studio (SSMS) from SQL Server 2019.
In my case there were undecipherable characters in the source data, which was exported to CSV from Excel. Some columns were in the "Accounting" format, which has spaces, currency symbols, commas, and parenthesis, like this:
To account for this and resolve the error, I simply inserted a nested
REPLACE()
function to remove some characters and replace others, and wrapped it withIsNull()
to return zero when necessary.First I will describe:
$
,
)
with nothing (aka null string or empty quotes''
)(
with-
(aka hyphen or negative symbol)And here is the SQL:
zxlwwiss3#
Convert float to nvarchar instead of nvarchar to float. Of course!