Error Inserting From Inner Join and EXCEPT clause SQL. conversion failed when converting the varchar value 'Error:' to data type int

Error Inserting From Inner Join and EXCEPT clause SQL. conversion failed when converting the varchar value 'Error:' to data type int

我有 3 table

Tabledocs2 日志表 Tabledocs1

我正在尝试从 Tabledocs1 中插入 Tabledocs2,而不是在 Tabledocs2 中。

LogTable 是中间体 table,它包含 Tabledocs1 和 Tabledocs2 的列。

按大小写转换不会捕获/处理此错误。 " 将 varchar 值 'Error:' 转换为数据类型 int 时转换失败

PRINT 'INSERTING FROM Tabledocs2 INTO Tabledocs1'
        INSERT INTO Tabledocs1 (Log_id, document_name , document_icon , document_body )
        SELECT  CONVERT(INT, CASE WHEN IsNumeric(CONVERT(VARCHAR(12),ID)) = 1 then CONVERT(VARCHAR(12), ID) else 0 End) as int  , document_name , document_icon , document_body 
        FROM LogTable
        INNER JOIN Tabledocs1 
        ON LogTable.detail_ID  = Tabledocs1.detail_ID 
        AND log_ID = @LogID 
        EXCEPT
        (SELECT Log_id, document_name , document_icon , document_body FROM Tabledocs2)--To Avoid duplicates

isnumeric() 可能会产生误导。在 sql 服务器 2012+ 中,请改用 try_convert()。对于失败的转换,它将 return null 而不是错误。

print 'INSERTING FROM Tabledocs2 INTO Tabledocs1'
insert into Tabledocs1 (
    Log_id
  , document_name
  , document_icon
  , document_body
 )
select 
    coalesce(try_convert(int,ID),0)
  , document_name
  , document_icon
  , document_body
from LogTable
  inner join Tabledocs1 
    on LogTable.detail_ID = Tabledocs1.detail_ID 
    and log_ID = @LogID
except
 select 
    Log_id
  , document_name
  , document_icon
  , document_body
 from Tabledocs2

也许你应该换个方向?

INSERT INTO Tabledocs1 (Log_id, document_name , document_icon , document_body )
    SELECT ID, document_name , document_icon , document_body 
    FROM LogTable INNER JOIN
         Tabledocs1 
         ON LogTable.detail_ID  = Tabledocs1.detail_ID 
    WHERE log_ID = @LogID 
    EXCEPT
    (SELECT CAST(Log_id as VARCHAR(12)), document_name , document_icon , document_body
     FROM Tabledocs2
    );--To Avoid duplicates

您可能出于某些原因(例如前导零)想要转换为数字格式。但是,12 个字符对于一个整数来说太长了,因此无论如何您都需要 NUMERIC()BIGINT