snippetsqlMinor
Create stored procedure inside try-catch block
Viewed 0 times
storedcreateblockcatchproceduretryinside
Problem
I'm using sqlserver 2014 and trying to create a
It fails to run with the error of:
Then i changed sp like:
I'm getting to conclude that creating
Is this even possible to create
StoredProcedure inside try-catch block like this:BEGIN TRY
CREATE PROCEDURE [ammeghezi1] (@w INT) AS SELECT ''
END TRY
BEGIN CATCH
...
END CATCHIt fails to run with the error of:
Incorrect syntax near 'SELECT' Expecting EXTERNAL.Then i changed sp like:
CREATE PROCEDURE [ammeghezi1] (@w INT) AS BEGIN SELECT '' END (cover sp with BEGIN-END block), But the error did not change. I also add GO after BEGIN TRY statement and it just got worst.I'm getting to conclude that creating
sp inside TRY_CATCH block is not practical. Is this even possible to create
sp inside TRY_CATCH block? And how?Solution
From the
The CREATE PROCEDURE statement cannot be combined with other
Transact-SQL statements in a single batch.
If you need a try/catch, you'll need to execute the DDL using dynamic SQL so that it is in a separate batch:
CREATE PROCEDURE documentation:The CREATE PROCEDURE statement cannot be combined with other
Transact-SQL statements in a single batch.
If you need a try/catch, you'll need to execute the DDL using dynamic SQL so that it is in a separate batch:
BEGIN TRY
DECLARE @CreateProcedureStatement nvarchar(MAX) =
N'CREATE PROCEDURE [ammeghezi1] (@w INT) AS SELECT ''''';
EXEC sp_executesql @CreateProcedureStatement;
END TRY
BEGIN CATCH
THROW;
END CATCH
GOCode Snippets
BEGIN TRY
DECLARE @CreateProcedureStatement nvarchar(MAX) =
N'CREATE PROCEDURE [ammeghezi1] (@w INT) AS SELECT ''''';
EXEC sp_executesql @CreateProcedureStatement;
END TRY
BEGIN CATCH
THROW;
END CATCH
GOContext
StackExchange Database Administrators Q#207262, answer score: 7
Revisions (0)
No revisions yet.