9

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?

4

3 回答 3

14

对于 SQL Server,您应该使用系统视图 sys.tables 来检查表是否存在。

IF EXISTS(SELECT 1 FROM B.sys.tables WHERE name = 'mytablebackup')
于 2013-10-02T14:48:44.450 回答
3

OBJECT_ID也可以使用:

IF OBJECT_ID('B.dbo.mytablebackup') IS NOT NULL
于 2019-12-17T23:00:20.420 回答
0

您可以直接从给定的 DB、SCHEMA 和 TABLE 参数中检查(对于动态数据库、模式和表使用)

DECLARE @targetdatabase  NVARCHAR(MAX),
        @SchemaName      NVARCHAR(MAX),
        @TableName       NVARCHAR(MAX)

DECLARE @TempTableName NVARCHAR(MAX) = QUOTENAME(@targetdatabase) + '.' + 
QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName)

IF OBJECT_ID(@TempTableName) IS NULL
BEGIN
    PRINT @TempTableName
END
于 2020-09-22T17:26:36.597 回答