SQL IF块代码即使不执行也会导致错误 [英] SQL IF block code causing error even though it shouldn't execute

查看:195
本文介绍了SQL IF块代码即使不执行也会导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有IF-ELSE块的SQL代码. IF部分中的代码不应该到达,但是在执行SQL时仍然出现错误.在我首先测试链接服务器的代码中,当失败时,@reval设置为1,并且ELSE块应执行并避免IF块中的代码需要查询链接服务器,但是我收到此错误:

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].

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

我正在从SSMS 2012中运行查询. 为什么会发生此错误?

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

-以下插入SQL语句导致错误

--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

推荐答案

在执行之前,它仍然会解析并绑定所有内容.无法绑定到这里.

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

您可以使用sp_executesql执行该行,并且它仅应在实际调用sp_executesql时进行验证.

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

这篇关于SQL IF块代码即使不执行也会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆