在IF语句中间执行GO命令

时间:2012-07-30 13:19:29

标签: sql-server tsql

我正在研究创建表,只有当它们不存在于当前数据库中时(为了能够在不同的数据库中创建它们,可能还是可能没有它们)并找到了这两个有用的主题

所以我做了这个查询

IF (NOT EXISTS (SELECT * 
             FROM INFORMATION_SCHEMA.TABLES 
             WHERE TABLE_NAME = 'EMAILCONTAS'))
BEGIN
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[EMAILCONTAS](
    [NRSEQEMAILCONTAS] [numeric](8, 0) NOT NULL,
    [CDEMAILCONTAS] [varchar](40) NULL,
    [MSGEMAILCONTAS] [varchar](4000) NOT NULL,
    [CCOEMAIL] [varchar](100) NULL,
    [NRSEQOPERADORA] [numeric](8, 0) NOT NULL,
 CONSTRAINT [PK_EMAILCONTAS] PRIMARY KEY CLUSTERED 
(
    [NRSEQEMAILCONTAS] 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

ALTER TABLE [dbo].[EMAILCONTAS]  WITH CHECK ADD FOREIGN KEY([NRSEQOPERADORA])
REFERENCES [dbo].[OPERADORA] ([NRSEQOPERADORA])
GO

ALTER TABLE [dbo].[EMAILCONTAS]  WITH CHECK ADD  CONSTRAINT [FK_EMAILCONTAS_OPERADORA] FOREIGN KEY([NRSEQOPERADORA])
REFERENCES [dbo].[OPERADORA] ([NRSEQOPERADORA])
GO

ALTER TABLE [dbo].[EMAILCONTAS] CHECK CONSTRAINT [FK_EMAILCONTAS_OPERADORA]
GO
END

但是当我执行它时,我在错误列表中得到了它。

Msg 102, Level 15, State 1, Line 5
Incorrect syntax near 'ON'.

但是无论如何它都创建了我的表(我在上面的代码之后放了一个“从PERSON中选择*”,以检查错误是否可能阻止下一个要编译的脚本。并且错误阻止了它。显示这个错误:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'Select'.

有办法避免它吗?)。当我执行此查询并且表已经存在时,我得到了跟随错误。

Msg 102, Level 15, State 1, Line 5
Incorrect syntax near 'ON'.
Msg 2714, Level 16, State 6, Line 2
There is already an object named 'EMAILCONTAS' in the database.
Msg 2714, Level 16, State 5, Line 2
There is already an object named 'FK_EMAILCONTAS_OPERADORA' in the database.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint. See previous errors.

如果没有收到这些错误,我怎么能做到这一点?有没有办法可以毫无问题地创建这样的多个代码?我做错了什么?

2 个答案:

答案 0 :(得分:2)

GO类似于脚本的结尾;您可以从BEGIN-END语句中删除GO

如果您绝对需要在代码中使用GO,则可以将查询分解为:

IF (criteria)
BEGIN
    ...
END

GO

IF (newcriteria)
BEGIN
    ...
END

答案 1 :(得分:1)

在我工作的地方,所有脚本都必须进行检查。在检查之前我有所有设置,如下例所示:

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].[DimTime]') AND type in (N'U'))
    BEGIN
        Create Table [dbo].[DimTime]
        (
            TimeID int PRIMARY KEY IDENTITY(1,1),
            Month int,
            Year int,
            Day int,
        )
    END