Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Nvarchar column to INT

Tags:

I have a nvarchar column in one of my tables. Now I need to convert that column values to INT type..

I have tried using

cast(A.my_NvarcharColumn as INT)  

and

convert (int, N'A.my_NvarcharColumn') 

When I ran my query I am getting errors like

Conversion failed when converting the nvarchar value ' 23454542 ' to data type int.

hi i am posting my entire code snippet

SELECT A.objID, name, des,  right(Replace(Ltrim(Replace(substring(my_nvarcharcolumn,1,9), '0', ' ')), ' ', '0'),10) AS new_nvarcharcolumn  INTO #tmp1 FROM [database].[dbo].[tblname] AS A INNER JOIN (SELECT * FROM [database].[dbo].tblname1 WHERE sourceID = 32) AS AI ON source = A.objID INNER JOIN [database].[dbo].tblname2 AS I ON I.ObjectID = A.Source  SELECT MAX(m_dAddDate) AS date_Asof, dnum INTO #tmp2 FROM  (SELECT * FROM [database].[dbo].tblname WHERE senior <> '' AND class = 'SSS') AS A GROUP BY dnum  SELECT DISTINCT A.* INTO #tmp3 FROM #tmp1 AS A INNER JOIN #tmp2 AS SD ON SD.dnum =cast(A.new_nvarcharcolumn as INT) INNER JOIN database.[dbo].tbl4 AS M ON M.dnum = cast(A.new_nvarcharcolumn as INT)  AND SD.date_Asof = M.adddate 
like image 237
user1348424 Avatar asked Oct 19 '12 05:10

user1348424


People also ask

Can we convert nvarchar to int in SQL?

1 Answer. "CONVERT" considers the column name, not the string that has the column name; your current expression is attempting to convert the string A. my_NvarcharColumn to an integer instead of the column content. SELECT convert (int, N'A.

Can you convert varchar to nvarchar?

NVARCHAR has higher precedence than the VARCHAR data type. Therefore, during the data type conversion, SQL Server converts the existing VARCHAR values into NVARCHAR.

Can we convert nvarchar to decimal in SQL?

You can code it to any decimal (18, 2) value. Here's one example that codes it to a NULL. The real question here is why you're storing numeric values in an nvarchar column. You should always pick the data type that's appropriate to the data you want to store.


1 Answers

CONVERT takes the column name, not a string containing the column name; your current expression tries to convert the string A.my_NvarcharColumn to an integer instead of the column content.

SELECT convert (int, N'A.my_NvarcharColumn') FROM A; 

should instead be

SELECT convert (int, A.my_NvarcharColumn) FROM A; 

Simple SQLfiddle here.

like image 59
Joachim Isaksson Avatar answered Oct 08 '22 00:10

Joachim Isaksson