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 Answer 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
-
1
'
is escaped in TSQL with''
David Browne - Microsoft– David Browne - Microsoft2021年04月19日 14:29:46 +00:00Commented Apr 19, 2021 at 14:29