SQL Server“varchar值的转换'99101500728'溢出了一个int列。”

时间:2018-05-21 16:51:13

标签: sql sql-server select

这是我的问题:当我运行此查询时,没有问题并按预期返回结果

SELECT * 
FROM a 
INNER JOIN b ON a.OpId = b.OpId
INNER JOIN c ON b.AdId = c.AdId
INNER JOIN d ON c.AdId = d.AdId
INNER JOIN e ON a.CId = e.CId
INNER JOIN f ON b.OpId = f.OpId
INNER JOIN g ON a.AdRId = g.AdRId
INNER JOIN s ON c.AdSId = s.AdSId 
WHERE f.document = '52147896'

但是,当我尝试使用EXEC命令执行它时,它不起作用!!

这是有问题的代码

declare @document varchar(20) = '52147896' --This is the correct type for this attribute since I took it directly from the table type
DECLARE @SELECT2 nvarchar(max) = 'SELECT * FROM a inner join  b ON 
a.OpId = b.OpId
INNER JOIN c ON b.AdId = c.AdId
INNER JOIN d ON c.AdId = d.AdId
INNER JOIN e ON a.CId = e.CId
INNER JOIN f ON b.OpId = f.OpId
INNER JOIN g ON a.AdRId = g.AdRId
INNER JOIN s ON c.AdSId = s.AdSId WHERE 
f.document = '+@document

这是我得到的错误:

  

Msg 248,Level 16,State 1,Line 1
  varchar值'99101500728'的转换溢出了一个int列。

有人可以帮我解决这个问题吗?

提前致谢

3 个答案:

答案 0 :(得分:4)

如果类型是字符串,则将值括在单引号中:

. . . 
f.document = '''+ @document + ''''

更好的是,使用参数并使用sp_executesql传递值。

答案 1 :(得分:3)

造成错误的区别在于这一行:

f.document = '52147896' -- Expression without EXEC

f.document = 52147896 -- Expression with EXEC

在第二种情况下,由于您要与整数值进行比较,因此SQL引用会将列f.document转换为整数以进行比较,如data type precedence所述。当它尝试转换时,varchar值'99101500728'对于int失败来说太大了。

要解决此问题,请通过在前后添加单引号将您的值写为字符串文字:

declare @document varchar(20) = '52147896' --This is the correct type for this attribute since I took it directly from the table type
DECLARE @SELECT2 nvarchar(max) = 'SELECT * FROM a inner join  b ON 
a.OpId = b.OpId
INNER JOIN c ON b.AdId = c.AdId
INNER JOIN d ON c.AdId = d.AdId
INNER JOIN e ON a.CId = e.CId
INNER JOIN f ON b.OpId = f.OpId
INNER JOIN g ON a.AdRId = g.AdRId
INNER JOIN s ON c.AdSId = s.AdSId WHERE 
f.document = '''+@document + ''''

答案 2 :(得分:1)

您的where子句传递整数值。

WHERE f.document = 52147896

这导致f.document隐式转换为INT数据类型。您的一个ID值的字符串为99101500728,但这不会转换为INT数据类型。

您可以通过转义单引号来修复动态SQL,以便WHERE子句将值作为字符串传递

'WHERE f.document = ''' + @document + ''''

将生成

WHERE f.document = '52147896'