I've encountered a problem executing a T-SQL statement (inserting and updating) on linked Oracle servers when executing the query twice.
The first execution works like a charm, but when trying a second time, I get this error:
The OLE DB provider "OraOLEDB.Oracle" for linked server "Linked_Server" supplied inconsistent metadata. An extra column was supplied during execution that was not found at compile time.
I've already looked it up and tried several approaches:
- Use of openquery instead of original statement as suggested here: MSSQL Linked Server error: The OLE DB provider "OraOLEDB.Oracle" for linked server supplied inconsistent metadata for a column
- Use
OPTION (RECOMPILE)
at the end of original statement as well as on the openquery statement as suggested here: https://dba.stackexchange.com/questions/275605/linked-server-throws-metadata-error or here https://learn.microsoft.com/en-us/answers/questions/98208/linked-server-throws-metadata-error.html
One thing I've encountered is when using OPTION (RECOMPILE)
the statement is infinite and I had to cancel it manually when executing the query the 2nd time.
Original statement:
declare @insert_cmd varchar(3000) = dbo.substringProc('
insert into LINKED_SERVER.TABLE (E_KNZ_NR, E_KNZZTRH_PERIODE_DAT, E_KNZZTRH_IST_WT, E_KNZZTRH_ERSTERF_TS)
select
id_dwh_knz,
monitor_dat,
monitor_wert,
SYSDATETIME()
from temp_nes_kennzahl zr
left outer join (
select
E_KNZ_NR,
periode_dat=cast(E_KNZZTRH_PERIODE_DAT as date),
E_KNZZTRH_IST_WT
from LINKED_SERVER2.TABLE
) dwh_zr
on zr.id_dwh_knz = dwh_zr.E_KNZ_NR
and zr.monitor_dat = dwh_zr.periode_dat
where dwh_zr.periode_dat is null
order by monitor_dat asc, id_dwh_knz asc ') -- OPTION (RECOMPILE)
exec (@insert_cmd);
Statement with openquery:
declare @insert_cmd varchar(3000) = dbo.substringProc('
insert into openquery (LINKED_SERVER, ''SELECT E_KNZ_NR, E_KNZZTRH_PERIODE_DAT, E_KNZZTRH_IST_WT, E_KNZZTRH_ERSTERF_TS FROM LINKED_SERVER.TABLE'')
select
id_dwh_knz,
monitor_dat,
monitor_wert,
SYSDATETIME()
from temp_nes_kennzahl zr
left outer join (
select * from openquery (LINKED_SERVER2,''SELECT E_KNZ_NR,CAST(E_KNZZTRH_PERIODE_DAT as DATE) AS periode_dat,E_KNZZTRH_IST_WT FROM LINKED_SERVER2.TABLE'')
) dwh_zr
on zr.id_dwh_knz = dwh_zr.E_KNZ_NR
and zr.monitor_dat = dwh_zr.periode_dat
where dwh_zr.periode_dat is null
order by monitor_dat asc, id_dwh_knz asc') -- OPTION (RECOMPILE)
exec (@insert_cmd);
(The 'substringProc' is just a helper method to retrieve the related user/database for production or test environment and 'dwh' stands for the datawarehouse at the linked oracle server)
Would be nice if someone got a solution for that, since I'm struggling with this error for quite a long time and both of the queries work - but only once. I've also read that there might be a problem with the execution plan stored in the cache but I have no clue how to workaround such an issue.
Thanks in advance