我只在当前数据库上不存在表时才查看有关创建表的内容(以便能够在可能或可能没有它们的不同数据库中创建它)并发现这两个有用的主题
所以我做了这个查询
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'.
但它无论如何都会创建我的表(我在上面的代码之后放置了一个“Select * from 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.
我怎么能做到这一点而不会出现这些错误?有没有办法可以毫无问题地创建多个这样的代码?我究竟做错了什么?