I have 3 tables
Tabledocs2 LogTable Tabledocs1
I am trying to insert into Tabledocs2 from Tabledocs1 not in Tabledocs2 already.
The LogTable is the intermediate table which contains the columns of Tabledocs1 and Tabledocs2.
Convert on case doesn't catch/ handle this error. " conversion failed when converting the varchar value 'Error:' to data type 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
Perhaps you should convert in the other direction?
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
There may be reasons -- such as leading zeros -- why you would want to convert to a numeric format. However, 12 characters is too long for an integer, so you would need NUMERIC()
or BIGINT
anyway.