0

I have a table that gets deleted and re created in milliseconds(cant just insert and delete). Of course this occurs sometimes when another stored procedure is running and trying to call that table. How would I avoid this? I have tried 'waitfor' xx seconds and different types of loops to wait until the table is back but I still get the error saying the table does not exist or (invalid object name 'xxxx') Thanks for any help.

2
  • you my have to post some sample code Commented Jan 22, 2016 at 13:36
  • 1
    What is the reason for dropping/recreating the table? Why not simply TRUNCATE the table? Commented Jan 22, 2016 at 15:15

2 Answers 2

1

Delete and recreate the table within a transaction.

When ever you read / write from / to it make sure you transaction isolation level is READ COMMITTED.

That way, the table should always be there as your read / writes won't happen until the transaction for deleting and creating the table is commited.

I think that's right, so I hope that helps.

enter link description here

Sign up to request clarification or add additional context in comments.

Comments

0

You need to check if the table exists before you try to access it. You can do something like:

IF (EXISTS (SELECT * 
                 FROM INFORMATION_SCHEMA.TABLES 
                 WHERE TABLE_SCHEMA = 'Schema' 
                 AND  TABLE_NAME = 'Table'))
BEGIN
    -- Do stuff with the table
END

Another option is to handle the schema errors by using TRY/CATCH together with dynamic SQL like this:

BEGIN TRY

DECLARE @sql nvarchar(100)

SET @sql = 'SELECT * FROM NonExistentTable'

EXEC sp_executesql @sql

END TRY

BEGIN CATCH

SELECT'Do stuff here'

END CATCH

6 Comments

This will also work but you need to specify the schema as well.
But if you you are "already in that schema" you don't. Fair point though as it is not clear if the OP is or isn't.
The if exist wont work if my table is gone for that split second. It will just give me a invalid object name error.
@Chris Do you mean the split second between the If exists check and the execution of the statements inside?
@CookieMonster Correct. Sometimes I do the exist and the table is truly there. Then my code below to get data from that table wont work because then that split second happens. Then we get the error. Is there a way to avoid getting that error and just rollback or delay a second so I can get my table? Hope this makes sense.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.