Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

sql server - What is wrong with my Try Catch in T-SQL?

I am using SQL Server 2008 and when I run this Statement in Management studio the Select statement in the Catch Block is executed as expected

BEGIN TRY
 INSERT INTO IDontExist(ProductID)
 VALUES(1)
END TRY
BEGIN CATCH
SELECT 'There was an error! ' + ERROR_MESSAGE()
END CATCH

However when I run this statement the statement in the Catch Block is never executed and instead the error is just displayed in the results tab

BEGIN TRY
  Select * from IDontExist
END TRY
BEGIN CATCH
  SELECT 'There was an error! ' + ERROR_MESSAGE()
END CATCH

They both return the same error number '208' 'Invalid Object Name: IDontExist' so why would one get handled and the other not?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't get the CATCH block hit at all.

That's because the code won't compile, because the object doesn't exist, no plan is generated, so nothing runs to hit the CATCH block.

You can never hit this catch block so somethign is wrong with your testing/example. You can hit an outer catch block in a different scope (eg nested stored procs)

Edit: I'm using SQL Server 2005 SP3

It depends when deferred name resolution applies, related to statement level recompilation.

  • In my case, the whole batch fails both times and no statement level recompilation happens so no deferred name resolution

  • In OP's case, the batch compiles and runs but then has a statement level recompilation/deferred name resolution error in running code

I'm off to find some references about why it's different, given BOL doesn't say much, neither does Erland Sommarskog


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...