Comandos GO no meio de uma instrução IF
Eu estava procurando SO sobre criar tabelas somente se elas não existissem no DataBase atual (para poder criá-lo em bancos de dados diferentes que MAIO ou NÃO PODEM tê-las já) e encontrei esses dois tópicos úteis
SQL Server: verifique se a tabela existeComo verificar se a coluna existe na tabela do SQL ServerEntão fiz essa consulta
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
Mas quando eu executo, eu entendi isso, na lista de erros.
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near 'ON'.
Mas cria minha mesa de qualquer maneira (Eu coloquei um "Select * from PERSON"; após o código acima, para verificar se o erro pode bloquear o próximo script a ser compilado ou não. E o erro bloqueou. Mostrando este erro:
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'Select'.
Existe uma maneira de evitar isso?). E quando eu executo essa consulta e a tabela já existe recebi os seguintes erros.
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.
Como eu poderia conseguir isso sem receber esses erros? Existe uma maneira que eu possa criar vários códigos como este sem problemas? O que estou fazendo de errado?