If 语句 - SQL

If statement - TSQL

我想要实现的是检查 table 是否存在:

下面是我的代码,但出现错误。

代码:

--Check if table exists
IF  EXISTS (SELECT * FROM sys.objects 
            WHERE object_id = OBJECT_ID(N'[dbo].[Com_SQL_Server_Agent_Monitor]') 
              AND type in (N'U'))
    TRUNCATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
ELSE
    --Create table if not exist
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO
 
    CREATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
    (
        [job_id] [uniqueidentifier] NULL,
        [originating_server] [nvarchar](30) NULL,
        [name] [nvarchar](128) NULL,
        [enabled] [tinyint] NULL,
        [description] [nvarchar](512) NULL,
        [start_step_id] [int] NULL,
        [category] [nvarchar](128) NULL,
        [owner] [nvarchar](128) NULL,
        [notify_level_eventlog] [int] NULL,
        [notify_level_email] [int] NULL,
        [notify_level_netsend] [int] NULL,
        [notify_level_page] [int] NULL,
        [notify_email_operator] [nvarchar](128) NULL,
        [notify_netsend_operator] [nvarchar](128) NULL,
        [notify_page_operator] [nvarchar](128) NULL,
        [delete_level] [int] NULL,
        [date_created] [datetime] NULL,
        [date_modified] [datetime] NULL,
        [version_number] [int] NULL,
        [last_run_date] [int] NULL,
        [last_run_time] [int] NULL,
        [last_run_outcome] [int] NULL,
        [next_run_date] [int] NULL,
        [next_run_time] [int] NULL,
        [next_run_schedule_id] [int] NULL,
        [current_execution_status] [int] NULL,
        [current_execution_step] [nvarchar](128) NULL,
        [current_retry_attempt] [int] NULL,
        [has_step] [int] NULL,
        [has_schedule] [int] NULL,
        [has_target] [int] NULL,
        [type] [int] NULL
    ) ON [PRIMARY]
GO

这是我得到的错误:

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

知道我遗漏了什么吗?

您代码中的最大问题是您的ELSE中有多个SQL语句 ] 块 - 但它们没有被 BEGIN ... END.

框住

所以真的你现在拥有的是:

IF  EXISTS (....)
    TRUNCATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
ELSE
    SET ANSI_NULLS ON

-- these statements will be executed ALWAYS - no matter what the
-- IF EXISTS() check returns!    
SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
......

因此,即使 table 存在并被截断 - SET QUOTED_IDENTIFIER ONCREATE TABLE 语句仍将被执行!这就是为什么您收到错误“table 已经存在”的原因。

您需要做的是:

IF EXISTS (....)
    TRUNCATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
ELSE
BEGIN
    SET ANSI_NULLS ON
    SET QUOTED_IDENTIFIER ON

    CREATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
    ......
END