我得到'转换失败时将nvarchar值'XXX'转换为数据类型int'错误没有明显的原因,我不知道如何解决它。该视图实际上将正确的数据返回给存储过程,但它给了我这个错误。我被卡住了。有人请给我一些指示吗?
SELECT d.Code, a.Agency, a.Agency_job, a.OUCode, a.JobCode, d.OraUser, c.ProfileName
FROM dbo.Agency AS a
LEFT OUTER JOIN dbo.IdM AS d ON REPLACE(STR(a.OUCode, 3), ' ', '0') = d.OrganizationUnitCode AND a.JobCode = d.JobCode
LEFT OUTER JOIN dbo.Profiles AS c ON c.JobCode = a.JobCode AND c.OUCode = a.OUCode
WHERE (d.Code IS NOT NULL)
列详细信息 -
d.Code is nvarchar(32),
d.OraUser is nvarchar(100),
d.OrganizationUnitCode is nvarchar(16),
a.Agency is int,
a.Agency_job is int,
a.OUCode is int,
a.JobCode is int,
c.ProfileName is varchar(100),
c.OUCode is int,
c.JobCode is int.
有没有人可能会发现潜在的问题?
答案 0 :(得分:2)
在您的查询中发生错误是正常的!
REPLACE(STR(a.OUCode,3),'','0')是字符串类型,但连接谓词右侧的d.OrganizationUnitCode是一个int。所以它不能在这里隐式地进行转换,要么将int字段转换为nvarchar,要么反过来。你可以尝试这样的事情:
施放(REPLACE(STR(a.OUCode,3),'','0')为int)= d.OrganizationUnitCode
答案 1 :(得分:1)
如果你有OUCode>在你的表中999,STR(a.OUCode,3)将返回***,当尝试转换为int时会给你错误
Conversion failed when converting the varchar value '***' to data type int.
在线图书:https://docs.microsoft.com/en-us/sql/t-sql/functions/str-transact-sql?view=sql-server-2017
When the expression exceeds the specified length, the string returns ** for the specified length.
我能看到的另一个问题是: 您的IdM表中JobCode的数据类型是什么?试试这个,看看它是否会返回任何结果:
SELECT JobCode FROM dbo.IdM WHERE ISNUMERIC(JobCode) = 0
答案 2 :(得分:0)
以下是答案:
SELECT d.Code, a.Agency, a.Agency_job, a.OUCode, a.JobCode, d.OraUser, c.ProfileName
FROM dbo.Agency AS a
LEFT OUTER JOIN dbo.IdM AS d ON CAST(REPLACE(STR(a.OUCode, 3), ' ', '0') AS NVARCHAR(16)) = d.OrganizationUnitCode AND a.JobCode = d.JobCode
LEFT OUTER JOIN dbo.Profiles AS c ON c.JobCode = a.JobCode AND c.OUCode = a.OUCode
WHERE (d.Code IS NOT NULL)
使用STR功能时也请选择正确的值。