【发布时间】:2021-11-11 05:29:47
【问题描述】:
我想要实现的是检查表是否存在:
- 如果存在,就截断它
- 如果不存在,则创建表
以下是我的代码,但出现错误。
代码:
--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”的对象
任何想法我缺少什么?
【问题讨论】:
-
GO是批处理分隔符,这里不需要 -
我要删除所有
GO吗? -
你为什么不试试看呢?
-
你提到了 T-SQL。什么版本的 SQL Server?使用
SELECT @@VERSION找出答案。现代版本的语法要短得多。 -
@marc_s 有两个选项,如果存在则截断,如果不存在则创建。
标签: sql-server if-statement create-table truncate