DDL在SQL Server 2005上的IF NOT EXISTS语句中没有正确执行

时间:2009-03-23 23:08:12

标签: sql-server sql-server-2005 ddl

我有一个相当复杂的数据库需要部署到各种服务器上,这些服务器可能有也可能没有已经在其上实现的数据库的现有部分。为了解决这个意外情况,我设置了以下测试:

USE [testDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[wcSites]') AND type in (N'U'))
begin
    CREATE TABLE [dbo].[wcSites](
        [id] [int] IDENTITY(1,1) NOT NULL,
        [name] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
        [siteCSS] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [masterTemplate] [int] NULL,
        [errorPage] [int] NULL,
        [homePage] [int] NULL,
        [addressProduction] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
        [addressTest] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
        [routeHandler] [varchar](100) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [publish] [bit] NOT NULL CONSTRAINT [DF_wcSites_publish]  DEFAULT ((0)),
        [publicAccess] [bit] NOT NULL CONSTRAINT [DF_wcSites_publicAccess]  DEFAULT ((1)),
        [siteAccessPermission] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
        [contentOwner] [int] NULL,
        [navStyle] [int] NULL,
        [incScripts] [int] NULL,
        [boxW] [int] NULL,
        [boxH] [int] NULL,
        [columns] [int] NULL,
        [rows] [int] NULL,
     CONSTRAINT [PK_wcSites] PRIMARY KEY CLUSTERED 
    (
        [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
     CONSTRAINT [IX_wcSites_Unique_Address] UNIQUE NONCLUSTERED 
    (
        [addressProduction] ASC,
        [addressTest] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO
    SET ANSI_PADDING OFF
    GO
    EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Ensure unique addresses in the addressProduction, addressTest fields' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'wcSites', @level2type=N'CONSTRAINT',@level2name=N'IX_wcSites_Unique_Address'
end

最终结果总是:

Msg 102, Level 15, State 1, Line 32
Incorrect syntax near 'PRIMARY'.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'end'.

如果我测试IF语句,它可以正常工作:

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[wcSites]') AND type in (N'U'))
begin
    PRINT 'Table does not exist'
end

同样在我测试CREATE TABLE脚本时。但是当我将CREATE TABLE脚本放在begin..end块中时,它每次都会失败。而且我遇到了全面的问题,几乎每个使用此方法的表都失败了。

2 个答案:

答案 0 :(得分:4)

尝试删除begin..end块中的'go'语句,看看是否有帮助。

答案 1 :(得分:0)

我对SQL Server语法有点模糊,但GO语句是否尝试执行Block?如果用分号替换go会怎么样?

另外,当设置Ansi_padding on在外面时,设置Ansi_padding off在If块中对我来说很奇怪,你确定这是正确的吗?