SQL IF block code causing error even though it shouldn't execute

跟風遠走 提交于 2019-12-14 03:52:59

问题


I have a case in which I have SQL code with an IF-ELSE block. The code in the IF portion should not be reached, but I still get an error when the SQL executes. In the code I first test for the linked server, and when that fails, @reval is set to 1 and the ELSE block should execute and avoid the code in the IF block that needs to query the linked server, but I get this error:

Msg -1, Level 16, State 1, Line 0 SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF].

I am running the query from within SSMS 2012. Why does this error occur?

declare @clientCode VARCHAR(7)
set @clientCode = '8001299'
declare @year INT
set @year = 2013

DECLARE @retVal INT        
-- test connectivity with linked database server
BEGIN TRY
       EXEC @retVal = sys.sp_testlinkedserver N'ATLAS'  
END TRY
BEGIN CATCH
       SET @retval = SIGN(@@ERROR)
END CATCH

IF @retval = 0 -- connection attempt successful 
BEGIN

--THE FOLLOWING INSERT SQL STATEMENT CAUSES THE ERROR

        SET @contIndex = (SELECT ContIndex FROM ATLAS.Engine_sp.dbo.tblEngagement WHERE ClientCode = @clientCode)          
END
ELSE -- could not connect 
BEGIN
       -- execute code to pull from linked server 
END

回答1:


It'll still parse and bind everything before it executes it. It's failing to bind here.

You could use sp_executesql to execute that line, and it should only validate when sp_executesql is actually called.



来源:https://stackoverflow.com/questions/21323075/sql-if-block-code-causing-error-even-though-it-shouldnt-execute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!