Sql-server – CREATE FUNCTION inside BEGIN TRY and END TRY

sql servert-sql

I want to use CREATE FUNCTION in a block that will "swallow" errors, but this

BEGIN TRY

CREATE FUNCTION test (@ID int)
RETURNS int
AS
BEGIN
    RETURN(2 * @ID)
END


END TRY
BEGIN CATCH
END CATCH 

results in

Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword
'FUNCTION'. Msg 137, Level 15, State 2, Line 7 Must declare the scalar
variable "@ID".

Why?

Best Answer

Many DDL statements must either start a batch or be the only statement in a batch. So the general solution is to use dynamic SQL. EG

I want to use CREATE FUNCTION in a block that will "swallow" errors, but this

BEGIN TRY

exec('
CREATE FUNCTION test (@ID int)
RETURNS int
AS
BEGIN
    RETURN(2 * @ID)
END
')

END TRY
BEGIN CATCH
END CATCH