首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >If语句- TSQL

If语句- TSQL
EN

Stack Overflow用户
提问于 2021-09-16 08:16:02
回答 1查看 70关注 0票数 0

我试图实现的是检查表是否存在:

如果存在

  • ,只需截断它
  • ,如果不存在,则创建表

下面是我的代码,但我得到了一个错误。

代码:

代码语言:javascript
运行
复制
--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

这是我得到的错误:

数据库中已经有一个名为“Com_SQL_Server_Agent_Monitor”的对象

知道我错过了什么吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-16 08:25:21

代码中最大的问题是,您的ELSE块中有多个SQL语句,但它们不是由BEGIN ... END构成的。

所以,,您现在拥有的是:

代码语言:javascript
运行
复制
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]
......

因此,即使该表存在并被截断-- SET QUOTED_IDENTIFIER ONCREATE TABLE语句仍将被执行!这就是为什么您要得到一个错误“表已经存在”。

你需要做的是:

代码语言:javascript
运行
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69204741

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档