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.