【问题标题】:Insert fails with first error, not all errors插入失败并出现第一个错误,而不是所有错误
【发布时间】:2017-12-22 03:05:16
【问题描述】:

长期以来,插入错误一直是返回第一条消息,而不是所有消息。以下返回“将数据类型 varchar 转换为数字时出错。”实际上有两个无效值。修复 columnB 的值后,我们会看到 columnC 的错误。如何在第一次尝试时查看所有消息?

CREATE TABLE [dbo].[Table_1](
[columnA] [varchar](50) NULL,
[ColumnB] decimal(2,0) NOT NULL,
ColumnC int null
) ON [PRIMARY]

GO
INSERT INTO [dbo].[Table_1]
       ([columnA]
       ,[ColumnB]
       ,ColumnC)
 VALUES
       (23,
       'a',
       'b')

【问题讨论】:

  • 你不能(至少使用insert)。 SQL Server 在第一次失败时停止。
  • 插入以外的选项呢?
  • 向表中插入数据的唯一方法是使用 INSERT(或 MERGE),因此 T-SQL 中没有其他选项,除非您想编写一些预先验证它的东西
  • 请记住,SQL Server 可以处理 large 数据集。您可能不同意 SQL Server 开发人员的决定,但他们认为,既然他们知道INSERT 将失败,那么可能参与更多工作来检测任何进一步的错误是没有意义的。

标签: sql-server sql-server-2017


【解决方案1】:

要执行此类操作,您可以在场景中使用单独的 try-catch 块,因为它只有几个字段。

begin try
    insert into table_1
    (columnA)
    values 
    ('any value')
end try
begin catch
    select ERROR_MESSAGE()
end catch

begin try
    insert into table_1
    (columnB)
    values 
    ('any value')
end try
begin catch
    select ERROR_MESSAGE()
end catch

begin try
    insert into table_1
    (columnC)
    values 
    ('any value')
end try
begin catch
    select ERROR_MESSAGE()
end catch

【讨论】:

猜你喜欢
  • 2016-03-12
  • 2023-03-26
  • 2020-10-10
  • 1970-01-01
  • 2021-09-25
  • 2012-07-18
  • 2011-08-24
  • 2020-02-09
  • 2012-09-24
相关资源
最近更新 更多