我想實作的是檢查一個表是否存在:
我想實作的是檢查一個表是否存在。
- 如果它存在,就截斷它
- 如果它不存在,則創建該表 。
下面是我的代碼,但是我得到了一個錯誤。
代碼:
--檢查表是否存在。
如果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 [dbo].
--創建表,如果不存在。
SET ANSI_NULLS ON
啟用
SET QUOTED_IDENTIFIER ON
啟用
CREATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor].
(
[job_id] [uniqueidentifier] NULL,
[originating_server] [nvarchar](30) NULL。
[name] [nvarchar](128) NULL,
[enabled] [tinyint] NULL,
[描述] [nvarchar](512) NULL。
[start_step_id] [int] NULL,
[類別] [nvarchar](128) NULL。
[所有者] [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'的物件
有什么想法嗎?
我錯過了什么?
uj5u.com熱心網友回復:
你的代碼中的最大的問題是你在ELSE塊中有多條SQL陳述句--但它們沒有被BEGIN ... END框住。END。
所以實際上你現在的情況是:
IF EXISTS(....)
TRUNCATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
ELSE [dbo].
SET ANSI_NULLS ON
--這些陳述句將一直被執行--無論什么時候
-- IF EXISTS()檢查的回傳值!
SET QUOTED_IDENTIFIER ON
啟用
CREATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
......
因此,即使表存在,并被截斷--SET QUOTED_IDENTIFIER ON和CREATE TABLE陳述句仍將被執行!
你需要做的是:
IF EXISTS (....)
TRUNCATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
ELSE [dbo].
BEGIN
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
CREATE TABLE [dbo].[Com_SQL_Server_Agent_Monitor]
......
END
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/307250.html
標籤:
