Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I want to create new function by script in my database. The script code is below:

IF Exists(Select * From sys.sysobjects A Where A.name =N'fn_myfunc' and xtype=N'FN') return;

CREATE FUNCTION fn_myfunc ()
returns varchar(10)
AS Begin
...
End

But when I execute the above script, SQL Server returns an error:

'CREATE FUNCTION' must be the first statement in a query batch.
share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

You need to do what SQL Server does when you script this from Management Studio:

IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE type = 'FN' AND name = 'fn_myfunc')
BEGIN
    DECLARE @sql NVARCHAR(MAX);
    SET @sql = N'CREATE FUNCTION ...';
    EXEC sp_executesql @sql;
END

Or you can say:

BEGIN TRY
    DROP FUNCTION dbo.fn_myfunc;
END TRY
BEGIN CATCH
    PRINT 'Function did not exist.';
END CATCH
GO
CREATE FUNCTION...

Or you can just say:

DROP FUNCTION dbo.fn_myfunc;
GO
CREATE FUNCTION...

(Here you will get an error message if the function doesn't already exist, but the script will continue from the next GO, so whether the drop worked or not, the function will still be (re-)created.)

Note that if you drop the function and re-create it, you will lose permissions and potentially dependency information as well.

share|improve this answer
    
Thank you very much. –  mehdi lotfi Jun 9 '12 at 5:10
    
so there is no keyword $$CREATE OR REPLACE$$ ? pity. –  zinking Jun 21 '12 at 2:00
    
@zinking no, but maybe in a future version. Please vote/comment: connect.microsoft.com/SQLServer/feedback/details/127219/… –  Aaron Bertrand Jun 21 '12 at 2:03
add comment

The error is pretty self-explanatory. There are a couple ways of fixing it.

  1. Separate the script into different batches in Management Studio using the GO pseudo-keyword, and DROP/CREATE the object. (Note that the keyword itself can be changed in Management Studio options, but this is the de facto setting, so I suggest leaving it alone).

    When you run a script (or the selected portion of a script), Management Studio separates each chunk of script between GOs, and sequentially sends the parts to SQL Server as separate batches.

  2. Use dynamic SQL to send a separate batch from within another batch.

    This is the preferred method, because then your script does not depend on external functionality to execute correctly. For example, if your application has a database update program, generally speaking it will load a script file and then execute it on the target server. Either you will have to add logic to separate the batches as Management Studio does (note: fraught with peril), or write the script in a way that the entire script can be executed successfully as a single batch.

    As mentioned in another answer, you can do a test/CREATE using this method (or some other combination of DROP/CREATE, etc.). What I prefer to do is create a stub object if the object doesn't exist, and then use ALTER <object> to actually do the creation or alteration. This approach doesn't drop dependencies, such as permissions or extended properties, and it isn't necessary to copy/paste error-prone logic to do the CREATE/ALTER in a single statement.

    Here is the template I use for creating or changing a scalar function. I'll leave it as an exercise for the reader to adapt this to other types of objects (stored procs, triggers, etc.).

IF NOT EXISTS(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[<schema>].[<function name>]') AND type IN ('FN', 'FS'))
    EXEC sp_executesql N'CREATE FUNCTION [<schema name>].[<function name>] (@a int) RETURNS int AS BEGIN /* Stub */ RETURN @a END'

EXEC sp_executesql N'
ALTER FUNCTION [<schema name>].[<function name>]
/* ... */
'
share|improve this answer
    
How can option 1 work here? Adding a GO actually ensures the script will break, since the IF will lead nowhere. –  Aaron Bertrand Jun 10 '12 at 13:25
    
@Aaron: I was thinking of the DROP/CREATE scenario -- edited. Thanks. –  Jon Seigel Jun 14 '12 at 23:17
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.