将 nvarchar 转换为 int 以在视图中加入 SQL 表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16282616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert nvarchar to int in order to join SQL tables in a view
提问by Charalampos Afionis
I want to create a view which will display the info from two tables joined by different type fields. The one field is nvarchar and the other one is int. I know i need to convert one type in the other but don't know how to do it. Any help would be greatly appreciated.
我想创建一个视图,该视图将显示由不同类型字段连接的两个表中的信息。一个字段是 nvarchar,另一个字段是 int。我知道我需要将一种类型转换为另一种类型,但不知道该怎么做。任何帮助将不胜感激。
SELECT dbo.co.co_num, dbo.pck_hdr.weight, dbo.STR_ShipTrack.TrackingNumber
FROM dbo.co
INNER JOIN dbo.pck_hdr ON dbo.co.co_num = dbo.pck_hdr.co_num INNER JOIN dbo.STR_ShipTrack ON dbo.pck_hdr.pack_num = dbo.STR_ShipTrack.Reference1
回答by Gordon Linoff
Looking at your code, I can't tell either what you should do.
看着你的代码,我不知道你应该做什么。
The SQL engine will do automatic conversions for the comparison. However, if might decide to convert the character field to an integer -- and then get an error.
SQL 引擎会为比较进行自动转换。但是,如果可能决定将字符字段转换为整数——然后得到一个错误。
So, just cast your int field to nvarchar:
因此,只需将您的 int 字段转换为 nvarchar:
cast(IntField as nvarchar(255))
The length doesn't matter for an nvarchar()
comparison.
长度不重要的nvarchar()
比较。
In your query, you would replace:
在您的查询中,您将替换:
ON dbo.pck_hdr.pack_num = dbo.STR_ShipTrack.Reference1
with:
和:
ON cast(dbo.pck_hdr.pack_num as nvarchar(255)) = dbo.STR_ShipTrack.Reference1