'CREATE FUNCTION' must be the first statement in a query batch. Entity Framework Code First
You can avoid the
should be the first statement in a batch file
error without adding GO statements by putting the sql inside an EXEC command:
Sql(EXEC('BEGIN CREATE FUNCTION etc'))
Reference:
https://stackoverflow.com/a/20352867/150342
You have to generate your code and execute it as dynamic sql.
DECLARE @Sql NVARCHAR(MAX)
SET @Sql =
'
IF OBJECT_ID(''fn_Test'') IS NOT NULL DROP FUNCTION fn_Test
GO
CREATE FUNCTION fn_Test(@a INT)
RETURNS INT
BEGIN
RETURN @a
END
'
IF 1 = 1
BEGIN
EXEC(@Sql)
END