【问题标题】:Conversion failed when converting the varchar value '0%' to data type int将 varchar 值“0%”转换为数据类型 int 时转换失败
【发布时间】:2017-07-06 14:03:26
【问题描述】:

我遇到了 SQL Server 问题。

我已经创建了一个这样的表:

create table Components 
(
    pk BIGINT NOT NULL PRIMARY KEY IDENTITY,
    id VARCHAR(50),
    descr VARCHAR(50),
    in_m INT,
    in_iy INT,
    p_fw VARCHAR(5000)
);

我正在尝试插入几个值:

insert into Components (id, descr, in_m, in_iy, p_fw) 
values ('FW000_A', '0%', 0, 0, '[0.0,0.0,0.0]'),
       ('FW000_B', '1%', 1, 1, '[1.0,1.0,1.0]');

我收到以下错误:

消息 245,第 16 级,状态 1,第 111 行
将 varchar 值“0%”转换为数据类型 int 时转换失败。

即使descr 列正确定义为varchar(50)

有人可以帮帮我吗?为什么 SQL Server 试图将我的字符串转换为 int 值?

【问题讨论】:

  • 您的代码在 SQL Server 2014 中适用于我。rextester.com/UOOT87695 您确定它与您刚刚创建的表相同吗?相同的架构等?
  • 我正在使用 SQL Server Express 2012 但是是的,我有“使用 mydb;”文件开头的语句。编辑:我尝试为创建和插入查询添加符号 [schema].[table],但我得到的结果与以前相同......
  • 如果您运行 SQL 跟踪(或使用 hibernatingrhinos.com/products/nhprof),实际通过网络传递的 SQL 是什么?
  • 数据库与模式不同。再检查一遍?像 mydb.dbo.components vs mydb.AnotherSchema.components
  • 代码在这里也可以正常工作:rextester.com/live/EAL20795

标签: sql sql-server


【解决方案1】:

您的问题缺少的是,您不仅有两个 values 行,而且其中一个具有用于 descr 列的整数文字,而不是字符串。

这个例子产生了同样的错误:

declare @t table (Descr varchar(50) not null)
insert into @t(Descr) values
('0%'),
(12)

我认为 SQL Server 首先尝试确定 values 子句中所有列的数据类型。使用数据类型优先规则,它观察一行中的 varchar 文字和另一行中的 int 文字,因此确定此列的整体类型为 int 并尝试执行导致错误。

在此过程中,它使用有关将要放置values 的目标表的任何信息,包括那里的列的数据类型。

【讨论】:

  • 你完全正确!!!第 2 列中有一个值 100 没有引号,大约在第 436 个插入的元组处。可能是我的 sql 自动代码生成器中的一个错误。但是,更重要的是,我学到了这个重要的概念During this process, it does not use any information about the target table into which the values are going to be placed, including the data types of the columns there. 感谢大家的支持,问题解决了!
【解决方案2】:

运行它并验证数据类型;

  sp_columns Components 

看起来'descr'实际上是一个整数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-01
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多