sql-server – 如何将Nvarchar列转换为INT

前端之家收集整理的这篇文章主要介绍了sql-server – 如何将Nvarchar列转换为INT前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的一个表中有一个nvarchar列.现在我需要将列值转换为INT类型..

我试过使用

cast(A.my_NvarcharColumn as INT)

convert (int,N'A.my_NvarcharColumn')

当我运行我的查询时,我收到错误

Conversion Failed when converting the nvarchar value ‘ 23454542 ‘ to
data type int.

嗨,我发布我的整个代码片段

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

解决方法

CONVERT采用列名称,而不是包含列名称的字符串;您当前的表达式尝试将字符串A.my_NvarcharColumn转换为整数,而不是列内容.
SELECT convert (int,N'A.my_NvarcharColumn') FROM A;

应该是

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

简单的sqlfiddle here.

原文链接:https://www.f2er.com/mssql/75089.html

猜你在找的MsSQL相关文章