SQL Server:检查是否存在两个表

时间:2015-12-31 15:32:07

标签: sql sql-server-2012

如果我只尝试删除并创建一个新表时,这是否正确?表B来自另一个SQL Server(相同版本的SQL Server 2012)

IF EXISTS ((SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TableA]')
           AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
           INTERSECT
           (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[AnotherServer].Database.dbo.TableB')
           AND OBJECTPROPERTY(id, N'IsUserTable') = 1))
BEGIN
    DROP TABLE TableA

    SELECT *
    INTO TableA
    FROM [AnotherServer].Database.dbo.TableB
END

2 个答案:

答案 0 :(得分:2)

我相信你对桌子存在的第二次检查是错误的:

(SELECT * FROM dbo.sysobjects 
 WHERE id = OBJECT_ID(N'[dbo].[AnotherServer].Database.dbo.TableB')

该表格应使用[server].[database].[schema].[tablename]限定名称引用 - 此处[dbo].不在此处,请将其删除并重试:

IF EXISTS (
            (SELECT * FROM dbo.sysobjects 
             WHERE id = OBJECT_ID(N'[dbo].[TableA]')
             AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
            INTERSECT
            (SELECT * FROM dbo.sysobjects 
             WHERE id = OBJECT_ID(N'[AnotherServer].[Database].[dbo].[TableB]')
             AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
          )
BEGIN
    DROP TABLE [dbo].[TableA]

    SELECT *
    INTO [dbo].[TableA]
    FROM [AnotherServer].[Database].[dbo].[TableB]
END

更新:不完全确定远程表是否会列在您的本地dbo.sysobjects目录视图中.....可以尝试此检查?

IF EXISTS (SELECT * FROM dbo.sysobjects 
           WHERE id = OBJECT_ID(N'[dbo].[TableA]')
           AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
   AND OBJECT_ID('[AnotherServer].[database].[dbo].[TableB]') IS NOT NULL

答案 1 :(得分:1)

您可以使用T-SQL函数检查表存在

OBJECT_ID("<table_name>")

因此,在您的情况下,T-SQL代码将是下一个

IF OBJECT_ID('dbo.TableA') IS NOT NULL
    AND OBJECT_ID('AnotherServer.database.dbo.TableB') IS NOT NULL
BEGIN
    DROP TABLE TableA

    INSERT INTO TableA
    SELECT * FROM AnotherServer.database.dbo.TableB
END

您可以在MSDN页面(https://msdn.microsoft.com/ru-ru/library/ms190328(v=sql.120).aspx

中找到其他信息