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?

asked Apr 19, 2021 at 14:20

1 Answer 1

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 
answered Apr 19, 2021 at 14:21
1
  • 1
    ' is escaped in TSQL with '' Commented Apr 19, 2021 at 14:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.