kissta kissta - 1 month ago 17
SQL Question

SQL Server TRY CATCH FINALLY

I have a scenario where I need something similar to

.NET's try-catch-finally block.


On my try I will
CREATE a #temp table
,
INSERT
data to it & process other data sets based on
#temp
.

On
CATCH
then
RAISERROR
.
Is it possible to have a
FINALLY
block to
DROP #temp
?
Below is the pseudo code:

BEGIN TRY
CREATE TABLE #temp
(
--columns
)
--Process data with other data sets
END TRY
BEGIN CATCH
EXECUTE usp_getErrorMessage
END CATCH
BEGIN FINALLY
DROP TABLE #temp
END FINALLY

Answer

Instead of creating a table you could just declare a table variable (which will automatically go away when the query ends).

BEGIN TRY
DECLARE @temp TABLE
(
    --columns
)
--do stuff
END TRY
BEGIN CATCH
--do other stuff
END CATCH
Comments