Unable to Use Transactions with Go statement in SQL Server 2008 - sql

BEGIN TRY
BEGIN TRANSACTION
SET ANSI_NULLS ON
Go
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION dbo.RerurnStaticValue
(
#value nvarchar(10)
)
RETURNS varchar(max)
AS
BEGIN
DECLARE
#ReturnValue nvarchar(10)
SET #ReturnValue = #value
RETURN #ReturnValue
END
COMMIT TRAN -- Transaction Success!
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
ROLLBACK TRAN --RollBack in case of Error
select ERROR_MESSAGE()
END CATCH
I am preparing a very long script and try to implement the transaction in the script so in case if there will be any error in my script it will not effect my database. But I am getting the error Create function must be the only statement in the batch when implementing transactions.
Please help.

I think the documentation on functions is pretty clear:
User-defined functions cannot be used to perform actions that modify
the database state.
COMMIT/ROLLBACK definitely fall into this category.
Use a stored procedure instead.

Related

Using multiple relating statements inside a stored procedure?

I am using TSQL. I found this stored procedure template in the internet.
I want to first create a table A and then create from table a the table C. Would this work?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRAN
SELECT Name into table_A From table1
COMMIT TRAN
BEGIN TRAN
SELECT Name into table_C From table_A
COMMIT TRAN
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
ROLLBACK TRAN
DECLARE #ErrorMessage NVARCHAR(4000);
DECLARE #ErrorSeverity INT;
DECLARE #ErrorState INT;
SELECT #ErrorMessage = ERROR_MESSAGE(),
#ErrorSeverity = ERROR_SEVERITY(),
#ErrorState = ERROR_STATE();
RAISERROR(#ErrorMessage, #ErrorSeverity, #ErrorState );
END CATCH
END
GO
FIRST - there is no need to write BEGIN TRANSACTION and COMMIT arround all SQL Statement that manipulate data or structures inside the database. SQL Server run in autocommit mode, which mean that every SQL statement (INSERT, DELETE, UPDATE, CREATE, ALTER...) has it own transacion scope. If you want to have a transaction involving many statement use only one transaction...
SECOND - The syntax of RAISERROR does not accept parameters for then 2nd and 3rd argument as shown in the doc (just press F1 on the command when in SSMS) :
RAISERROR ( { msg_id | msg_str | #local_variable }
{ ,severity ,state }
[ ,argument [ ,...n ] ] )
[ WITH option [ ,...n
As you see, only the message can be argued as a local variable (it is why you get the error...)
Severity must be 16 which is the reserved class of developper error raising.
1 is the default state, but this is no more used...
THIRD - because the transaction is not systematically began whe entering in the CATCH part, you need to test if the transaction is alive or not with the XACT_STATE() function
FOURTH - it is preferable to use THROW instead of RAISERROR as the doc says...
FITH - Instead of writing separates command DECLARE and a SELECT for assignement, you can declare and set simultaneously
SIXTH - terminate all your TSQL sentences with a semicolon
Well now you have the code :
CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION;
SELECT Name into table_A From table1;
SELECT Name into table_C From table_A;
COMMIT TRAN;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0
ROLLBACK TRAN;
DECLARE #ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
THROW 55555, #ErrorMessage, 1;
END CATCH
END
GO
It will definitely work. Stored Procedure allows you to have multiple statement (create table, insert, update, index) and many more.
The best way to handle exceptions in SQL is, oddly enough, to not handle them at all.
If you catch the exception, and there are multiple messages, you lose that info. You also prevent the exception from bubbling up properly to the client. It only looks like a strange SELECT.
Furthermore, you can't catch all exceptions anyway. There are a number of fatal exceptions which are un-catchable.
So the best thing to do is to just use XACT_ABORT ON to ensure that any transactions are always rolled back and not left hanging. Note that not every query needs a transaction, only if you want to do multiple things atomically.
You should also use NOCOUNT ON for performance reasons
CREATE OR ALTER Procedure_Name
AS
SET XACT_ABORT, NOCOUNT ON;
SELECT 'Something';
GO
CREATE OR ALTER Procedure_Name
AS
SET XACT_ABORT, NOCOUNT ON;
BEGIN TRAN;
UPDATE SomeTable....;
INSERT SomeTable....;
COMMIT;
GO

Create SQL Server procedure in a transaction

I need to create two procedures in a SQL Server transaction. If failure, I need to rollback the create(s) and any other executed queries in this transaction. I know the create statement must be the first statement in query batch, but I need to know how handle the transaction with multiple batches.
BEGIN TRANSACTION
CREATE PROCEDURE [dbo].[SP_SP-1]
#id BIGINT
AS
BEGIN
SET NOCOUNT ON;
-- SQL statements
END
GO
CREATE PROCEDURE [dbo].[SP_SP-2]
#id BIGINT
AS
BEGIN
SET NOCOUNT ON;
-- SP-2 statements
END
GO
UPDATE Table
SET Value = '1.0.0.5'
COMMIT TRANSACTION / ROLLBACK TRANSACTION
Below is one method to execute multiple batches in a transaction. This uses a temp table to indicate if any batch erred and perform a final COMMIT or ROLLLBACK accordingly.
Another method is to encapsulate statements that must be in single-statement batch (CREATE PROCEDURE, CREATE VIEW, etc.) but that can get rather ugly when quotes within the literal text must be escaped.
CREATE TABLE #errors (error varchar(5));
GO
BEGIN TRANSACTION
GO
CREATE PROCEDURE [dbo].[USP_SP-1]
#id bigint
AS
BEGIN
SET NOCOUNT ON;
-- SP Statments
END;
GO
IF ##ERROR <> 0 INSERT INTO #errors VALUES('error');
GO
CREATE PROCEDURE [dbo].[USP_SP-2]
#id BIGINT
AS
BEGIN
SET NOCOUNT ON;
-- SP-2 Statments
END;
GO
IF ##ERROR <> 0 INSERT INTO #errors VALUES('error');
GO
UPDATE Table SET Value='1.0.0.5'
GO
IF ##ERROR <> 0 INSERT INTO #errors VALUES('error');
GO
IF EXISTS(SELECT 1 FROM #errors)
BEGIN
IF ##TRANCOUNT > 0 ROLLBACK;
END
ELSE
BEGIN
IF ##TRANCOUNT > 0 COMMIT;
END;
GO
IF OBJECT_ID(N'tempdb..#errors', 'U') IS NOT NULL
DROP TABLE #errors;
GO
I suggest you to study more about this subject in Handling Transactions in Nested SQL Server Stored Procedures.
From the beginning, your syntax is wrong. You cannot begin a transaction and then create a procedure, you need to do just the opposite:
CREATE PROCEDURE [dbo].[SP_SP-1]
#id bigint
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION
SET NOCOUNT ON;
-- SP-2 Statments
Update Table set Value='1.0.0.5'
END TRY
BEGIN CATCH
--handle error and perform rollback
ROLLBACK
SELECT ERROR_NUMBER() AS ErrorNumber
SELECT ERROR_MESSAGE() AS ErrorMessage
END CATCH
END
It is best practice to use TRY and CATCH when attempting to perform update inside transaction scope.
Please read more and investigate using the link I provided to get a bigger picture.
To use Transaction, you need to know what is the meaning of transaction. It's meaning of 'Unit of work either in commit state or rollback state'.
So when you use transaction, you must know that where you declare and where you close. So you must start and end transaction in the parent procedure only than it will work as a unit of work i.e. whatever no of query execute of DML statement, it uses the same transaction.
I do not understand why your update statement outside of procedure and transaction portion too.
It should be (See my comments, you can use TRY Catch same as c sharp) :
Create PROCEDURE [dbo].[SP_SP-1]
#id bigint
AS
BEGIN
Begin Transaction
SET NOCOUNT ON;
-- SP Statments
Exec SP_SP-2 #id --here you can pass the parameter to another procedure, but do not use transaction in another procedure, other wise it will create another transaction
If ##Error > 0 than
Rollback
Else
Commit
End
END
GO
--Do not use transaction in another procedure, otherwise, it will create another transaction which has own rollback and commit and do not participate in the parent transaction
Create PROCEDURE [dbo].[SP_SP-2]
#id BIGINT
AS
BEGIN
SET NOCOUNT ON;
-- SP-2 Statments
END
GO
i find this solution to execute the procedure as string execution , it`s a workaround to execute what i want
Begin Try
Begin Transaction
EXEC ('
Create PROCEDURE [dbo].[SP_1]
#id bigint
AS
BEGIN
SET NOCOUNT ON;
SP-1
END
GO
Create PROCEDURE [dbo].[SP_Inc_Discovery_RunDoc]
#id bigint
AS
BEGIN
SET NOCOUNT ON;
Sp-2
END')
Update Table set Value='1.0.0.5'
Commit
End Try
Begin Catch
Rollback
Declare #Msg nvarchar(max)
Select #Msg=Error_Message();
RaisError('Error Occured: %s', 20, 101,#Msg) With Log;
End Catch

Managing transaction in stored procedure with Dynamic SQL

I have a stored procedure with Dynamic SQL. Is it possible to include a batch of dynamic SQL inside an explicit transaction with COMMIT or ROLLBACK depending on the value of ##ERROR?
Following similar stored procedure. It is simplified in order to demonstration purpose.
CREATE PROCEDURE [dbo].[sp_Example]
AS
BEGIN
BEGIN TRANSACTION
DECLARE #ID VARCHAR(10)
INSERT INTO [dbo].[Deparment] (Name,Location,PhoneNumber) VALUES ('DeparmentName','DeparmentLocation','0112232332')
SELECT #ID =SCOPE_IDENTITY()
IF ##ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error in Inserting Deparment.', 16, 1)
RETURN
END
SET #InsertQuery = '
DECLARE #Name varchar(100)
SELECT #Name = Name
FROM dbo.[Deparment]
WHERE DepartmentId= ''' + #ID +'''
INSERT INTO [dbo].[Employee](Name,Age,Salary,DepartmentName)VALUES(''EMPLOYEE NAME'',''25'',''200000'','''+#NAME'')''
EXEC(#InsertQuery)
IF ##ERROR <> 0
BEGIN
ROLLBACK
RAISERROR ('Error in Inserting Employee.', 16, 1)
RETURN
END
COMMIT
END
Does outer Transaction scope applies to Dynamic query ?
The "outer" transaction will apply to everything that is executed. There is no way in SQL Server to not execute under the running transaction (which can be annoying of you want to log errors).

Can't use throw or raiseerror inside try..catch block in SQL Server stored procedure

I have this stored procedure and I can't use Throw or RAISEERROR for some reason. I have to say I am a newbie in SQL Server, I have never used this statements before, but for some reason when I type them in doesn't turn blue.
ALTER PROCEDURE [dbo].[del_pay_plan_proc]
#id INT
AS
BEGIN TRANSACTION
BEGIN TRY
DELETE FROM test_table WHERE [Id] = #id;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
THROW
END CATCH
I am using SQL Server 2008 R2.
What can be the reason that I can't call the function RAISEERROR or use THROW statement?
Thanks in advance!
As per my understanding it should be like below...
ALTER PROCEDURE [dbo].[del_pay_plan_proc]
#id INT
AS
Begin Try
SET NOCOUNT ON
SET XACT_ABORT ON
Begin Tran
DELETE FROM test_table WHERE [Id] = #id;
Select '' Msg
Commit Tran
End Try
Begin Catch
RollBack Tran
Select Error_Message() as Msg
End Catch
By doing this, it is not required to throw any Exception if an error occurs. Control will automatically move inside Catch block in case any error occurs.
Reference from here

Begin Transaction ... Commit Transaction Issue

i have a question regarding using Transaction. Consider this code:
declare #trans_name varchar(max) = 'Append'
begin tran #trans_name
insert into SIDB_Module
(module_name, module_description, modulelevel, parentid, issystem, iscurrent)
values
(#module_name, #module_description, #modulelevel, #parentid, #issystem, 1)
set #moduleid = SCOPE_IDENTITY()
declare #id int = OBJECT_ID('SIDB_Module')
exec usp_M_SIDB_TransactionInformation_App_Append
#moduleid, id, 'append' ,#createdby_userid
if ##ERROR <> 0
rollback tran #trans_name
commit tran #trans_name
does transaction still apply on this.. even the next insert query is on the other stored procedure??
Yes, the call to usp_M_SIDB_TransactionInformation_App_Append is part of the transaction
Note: your error handling is "old style" (using ##ERROR) from SQL Server 2000 and will generate errors (error 266) if the inner proc rolls back or commits.
For more, see Nested stored procedures containing TRY CATCH ROLLBACK pattern?