简体   繁体   English

将 nvarchar 转换为 int 以便在视图中连接 SQL 表

[英]Convert nvarchar to int in order to join SQL tables in a view

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.一个字段是 nvarchar,另一个是 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.任何帮助将不胜感激。

    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

Looking at your code, I can't tell either what you should do.查看您的代码,我无法告诉您应该做什么。

The SQL engine will do automatic conversions for the comparison. SQL 引擎将为比较进行自动转换。 However, if might decide to convert the character field to an integer -- and then get an error.但是,如果可能决定将字符字段转换为整数 - 然后会出现错误。

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

If you're casting from a string to an integer there's always a possibility you'll have a non-numeric content in the source column.如果您从字符串转换为整数,则始终有可能在源列中包含非数字内容。

INNER JOIN Tab t on t.ColId = CONVERT(int, CASE WHEN ISNUMERIC(strCol) = 1 THEN strCol ELSE '-1' END)

Similar to @gordon-linhoff answer.类似于@gordon-linhoff 的答案。 But doing the comparison as int rather than string.但是将比较作为 int 而不是 string 进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM