Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check existence of a table from a different sql db?

I have db A and db B. At the beginning of a stored procedure I want to back up all rows from B.mytable to B.mytablebackup. The rest of the stored procedure runs against tables on db A (which gathers data and writes it to B.mytable).

So I check to see if B.mytablebackup exists

IF EXISTS(SELECT 1 FROM B.dbo.mytablebackup)

and if it does, the stored procedure does an

INSERT INTO B..mytablebackup SELECT * FROM B..mytable

If it doesn't exist it does a

SELECT * INTO B..mytablebackup from B..mytable

But when I execute the stored procedure I get the error

There is already an object named 'mytablebackup' in the database

I added a Print statement and execution is taking the "does not exist" branch of the IF.

What am I doing wrong?

like image 271
DeveloperM Avatar asked Oct 02 '13 14:10

DeveloperM


People also ask

How do you check whether a table exists in database or not?

Using the OBJECT_ID and the IF ELSE statement to check whether a table exists or not. Alternative 2 : Using the INFORMATION_SCHEMA. TABLES and SQL EXISTS Operator to check whether a table exists or not.

How do you check if a table is being used in SQL Server?

Look in sys. dm_db_index_usage_stats. The columns last_user_xxx will contain the last time the table was accessed from user requests. This table resets its tracking after a server restart, so you must leave it running for a while before relying on its data.

How do you check if a data exists in SQL query?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.


2 Answers

OBJECT_ID can be used too:

IF OBJECT_ID('B.dbo.mytablebackup') IS NOT NULL
like image 104
vladimir Avatar answered Sep 19 '22 07:09

vladimir


For SQL Server, you should use system view sys.tables to check if table exists.

IF EXISTS(SELECT 1 FROM B.sys.tables WHERE name = 'mytablebackup')
like image 24
EricZ Avatar answered Sep 21 '22 07:09

EricZ