Para tabelas eu posso implementar "se não existir" e "se existir" como segue:
--if table exists - drop
If OBJECT_ID('A','U') is not null
Drop Table [A]
--if table not exists - Create
If OBJECT_ID('A','U') is null
Create Table A([key] varchar(20), [value] varchar(max))
mas não está funcionando da mesma forma em visualizações e gatilhos
Eu posso fazer:
-- if exists - drop
If OBJECT_ID('VA','V') is not null
Drop view [VA]
mas quando estou tentando o oposto:
-- if not exists - create
If OBJECT_ID('VA','V') is null
Create view [VA] as Select * from [A]
Estou recebendo o seguinte erro:
Sintaxe incorreta perto da palavra-chave 'view'
E o mesmo acontece com os gatilhos. quando eu faço:
-- if not exists - create
If OBJECT_ID('Trigger_A_ins','TR') is null
Create trigger [Trigger_A_ins] On [A] instead of insert As
insert into A select * from inserted
Estou recebendo erro:
Sintaxe incorreta perto da palavra-chave 'trigger'
Mas:
-- if exists - drop
If OBJECT_ID('Trigger_A_ins','TR') is not null
Drop Trigger Trigger_A_ins
está funcionando.
Eu perdi alguma coisa?
Alguém pode explicar essa diferença entre tabelas para triggers e views?
Obs: estou usando o sql server 2012
Fazendo referência à documentação de CREATE VIEW em OBSERVAÇÕES:
Referenciando a documentação de CREATE TRIGGER
Para
VIEWS
eTRIGGERS
, acho que você terá que verificar a existência do objeto e soltar em um lote e criá-los em outro lote separado por umGO
Exemplo:
Se você ainda precisar disso no mesmo lote, poderá usar o SQL dinâmico.