sql server - How to terminate SQL script before creating procedure or function -


i have following script in sql server 2014 creating scalar function named getfiscalperiod. script must check existence of function name before creating it.

use [databasename] go set ansi_nulls on go set quoted_identifier on go  if exists (select * dbo.sysobjects       id = object_id(n'[dbo].[getfiscalperiod]')       , objectproperty(id, n'isscalarfunction') = 1) --want terminate whole batch return --doesn't work way want --seems terminate if batch go  create function [dbo].[getfiscalperiod] () returns int begin     return (select max(id) dbo.__fiscalperiod__); end 

i want terminate whole thing reaches inside if body. (return)

the problem no matter how change code, either jumps create function giving error:

there object named 'getfiscalperiod' in database.

or giving syntax error (when try put create function in if clause):

'create function' must first statement in query batch.

question is:

is there anyway tell sql ignore rest of script when object name exists?

note:

i used drop function beforehand, , works. don't want drop , recreate every time.

... if exists (select * dbo.sysobjects       id = object_id(n'[dbo].[getfiscalperiod]')       , objectproperty(id, n'isscalarfunction') = 1) drop function [dbo].[getfiscalperiod] --works go  create function [dbo].[getfiscalperiod] () ... 

you can check existence, if existed alter else create: must exec query string.

if not exists (select * dbo.sysobjects id = object_id(n'[dbo].[getfiscalperiod]') , objectproperty(id, n'isscalarfunction') = 1) execute sp_executesql n' create function [dbo].[getfiscalperiod] ()  returns int begin     return (select max(id) dbo.__fiscalperiod__); end' else n' alter function [dbo].[getfiscalperiod] ()  returns int begin     return (select max(id) dbo.__fiscalperiod__); end' 

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -