0

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?

1

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 
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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