Transact SQL Skips GOTO or IF ELSE If linked server is in code

I am trying to solve the problem: "do not execute oracle query if server is unavailable", Script checks if LINKED ORACLE server is available and updates SQL Server with results Like below:

declare @srvr nvarchar(128), @retval int;
set @srvr = 'ORA_SVC';
begin try
  exec @retval = sys.sp_testlinkedserver @srvr;
end try
begin catch
  set @retval = sign(@@error);
end catch;
if @retval = 1 Update ORACLE_AVAIL set AVAILABLE = 0
if @retval = 0 Update ORACLE_AVAIL set AVAILABLE = 1
go

      

So ... the above code works great! And if I kill the ORACLE connection by modifying the TNSNames.ORA file ... wait for the SQL server to refresh its connection, the above code cannot find the linked server and update the database so we are good here.

After GO above this code and my problem.

DECLARE @ORACLE_ACTIVE BIT
set @ORACLE_ACTIVE = (select AVAILABLE from ORACLE_AVAIL)

if @ORACLE_ACTIVE = 1 GOTO ORACLE_IS_DOWN

INSERT into MY_SQL_SERVER_TABLE (COLUMN1,COLUMN2,COLUMN3)
select COLUMN1,COLUMN2,COLUMN3 from ORA_SVC..ORA_SVC.ORACLE_TABLE 

ORACLE_IS_DOWN:

      

The above portion of my Script will fail if the Oracle server is not offline, regardless of the @Oracle_Avail If statement.

If I change the code to;

DECLARE @ORACLE_ACTIVE BIT
set @ORACLE_ACTIVE = (select AVAILABLE from ORACLE_AVAIL)

if @ORACLE_ACTIVE = 1 GOTO ORACLE_IS_DOWN

PRINT 'GOTO DIDNT WORK'

ORACLE_IS_DOWN:

      

The print statement is ignored as expected. If @ORACLE_ACTIVE = 1, that is.

GOTO is bad, I understand. IF ELSE also fails if the linked server does not exist (the TNSNames.ora file points to an invalid host), the Script will fail if the @ORACLE_ACTIVE check fails.

Thank you for your time. I really hope I have phrased this correctly as I have not found a solution with search engines

+3


source to share


1 answer


I am assuming that during parsing, SQL Server is trying to validate your query. It may be trying to see if the columns exist.

You can defer parsing by moving the query to the inner scope:



exec N'INSERT into MY_SQL_SERVER_TABLE (COLUMN1,COLUMN2,COLUMN3)
       select COLUMN1,COLUMN2,COLUMN3 from ORA_SVC..ORA_SVC.ORACLE_TABLE'

      

+1


source







All Articles