SQL Server Student Guide-2
SQL Server Student Guide-2
Rationale
Databases are an integral part of an organization. Aspiring
database developers should be able to efficiently
implement and maintain databases. This knowledge will
enable them to build robust database solutions.
Objectives
After completing this course, the student should be able to:
Identify SQL Server tools
Query data from a single table
Query data from multiple tables
Manage databases and tables
Manipulate data in tables
Implement indexes, views, and full-text search
Implement stored procedures and functions
Implement triggers and transactions
Implement managed code
Implement services for message-based
communication
Entry Profile
The students who want to take this course should have:
Knowledge of RDBMS concepts.
Basic knowledge of computers.
Exit Profile
the data is to be inserted. The INTO keyword is optional.
column_list specifies an optional parameter. You can
use it when partial data is to be inserted in a table or when
Chapter 5 the columns to be inserted are defined in a different order.
DEFAULT specifies the clause that you can use to insert
Manipulating Data in Tables the default value specified for the column. If a default
value is not specified for a column and the column
After creating a database and tables, the next step is to property is specified as NULL, NULL is inserted in the
store data in the database. As a database developer, you column. If the column does not have any default constraint
will be required to update or delete data. You can perform attached to it and does not allow NULL as the column
these data manipulations by using the DML statements of value, SQL Server returns an error message and the insert
T-SQL. operation is rejected.
The data stored in the database can be used by different values_list specifies the list of values for the table
types of client applications, such as mobile devices or Web columns that have to be inserted as a row in the table. If a
applications. Therefore, data should be stored in a format column has to contain a default value, you can use the
that can be interpreted by any application. For this, SQL DEFAULT keyword instead of a column value. The
Server allows you to store data in the XML format that can column value can also be an expression.
be read by any application. select_statement specifies a nested SELECT
This chapter discusses how to use the DML statements to statement that you can use to insert rows into the table.
manipulate data in the tables. In addition, it explains how
to manipulate the XML data in the database tables. Guidelines for Inserting Rows
While inserting rows into a table, you need to consider the
Objectives following guidelines:
The number of data values must be the same as
In this chapter, you will learn to: the number of attributes in the table or column
Manipulate data by using DML statements list.
Manipulate XML data The order of inserting the information must be the
same as the order in which attributes are listed for
insertion.
Manipulating Data by Using DML The values clause need not contain the column
Statements with the IDENTITY property.
The data types of the information must match the
As a database developer, you need to regularly insert, data types of the columns of the table.
update, or delete data. These operations ensure that the Consider an example of the EmpData table that is used to
data is up-to-date. For example, you need to insert new store the details of the employees.
records in the Employee table whenever a new employee The following table describes the structure of the
joins the organization. EmpData table.
Similarly, if the details of an employee change, you need
to update the existing records. For example, if the salary of
Column Name Data Type Checks
any employee increases, you need to update the existing
records to reflect this change. EmpName varchar(20) NULL
You can use the DML statements to manipulate the data in EmpNo Int NOT NULL
any table. EmpAddress varchar(60) NULL
Salary Int NULL
Reference Reading
Manipulating Data by Using DML
Statements
Reference Reading
Implementing Batches
Implementing Functions
DDL Triggers
DDL triggers are fired in response to DDL statements,
such as CREATE TABLE or ALTER TABLE. They can be
used to perform administrative tasks, such as database
auditing. Database auditing helps in monitoring DDL
operations on a database. DDL operations can include
operations such as creation of a table or view, or
modification of a table or procedure. Consider an example,
where you want the database administrator to be notified A Direct Recursive Trigger
whenever a table is created in the master database. For this Indirect Recursive Triggers
purpose, you can create a DDL trigger. An indirect recursive trigger fires a trigger on another
table and eventually the nested trigger ends up firing the
Nested Triggers
first trigger again. For instance, an UPDATE statement on
Table A fires a trigger that, in turn, fires an update on
Table B. The update on Table B fires another trigger that Creating Triggers
performs an update on Table C. Table C has a trigger that
You can use the CREATE TRIGGER statement to create
causes an update on Table A again. As a result, the
triggers. The syntax of the CREATE TRIGGER statement
UPDATE trigger of Table A is fired again. The following
is:
figure depicts the execution of an indirect recursive
CREATE TRIGGER trigger_name
trigger.
ON { table | view }
{ FOR | AFTER | INSTEAD OF }
[WITH [ENCRYPTION] [EXECUTE AS] ]
{ AS
{ sql_statement [ ...n ] }
}
where,
trigger_name specifies the name of the trigger to be
created.
table | view specifies the name of the table or view
on which the trigger is to be created.
FOR | AFTER | INSTEAD OF specifies the
precedence and execution context of a trigger.
WITH ENCRYPTION encrypts the text of the CREATE
An Indirect Recursive Trigger TRIGGER statement.
EXECUTE AS specifies the security context under which
the trigger is executed.
AS sql_statement specifies the trigger conditions
and actions. A trigger can contain any number of T-SQL
statements, provided these are enclosed within the
BEGIN and END keywords.
For example, the following statement creates a trigger on
the HumanResources.Department table of the
AdventureWorks database:
CREATE TRIGGER [HumanResources].
[trgDepartment] ON [HumanResources].
[Department]
AFTER UPDATE AS
BEGIN
UPDATE [HumanResources].[Department]
SET [HumanResources].[Department].
[ModifiedDate] = GETDATE()
FROM Inserted
WHERE Inserted.[DepartmentID] =
[HumanResources].[Department].
[DepartmentID];
END;
The preceding statement creates a trigger named
trgDepartment. This trigger is fired on every successfully
executed UPDATE statement on the
HumanResources.Department table. The trigger updates
the ModifiedDate column of every updated value with the
current date.
The following statement creates a trigger to display the
data that is inserted in the magic tables:
CREATE TRIGGER trgMagic ON
EmpDeptHistory
AFTER UPDATE AS Hence, cannot insert.'
BEGIN ROLLBACK TRANSACTION
SELECT * FROM Deleted END
SELECT * FROM Inserted RETURN
END;
The preceding statement creates an AFTER UPDATE
The ROLLBACK TRANSACTION statement is used to
trigger on the EmpDeptHistory table. Whenever an
roll back transactions. The ROLLBACK TRANSACTION
UPDATE statement is fired on the EmpDeptHistory table, statement in the trgInsertShift trigger is used to undo the
the trgMagic trigger is executed and displays the previous insert operation.
value in the table as well as the updated value.
Creating a DELETE Trigger
A DELETE trigger gets fired at the time of deleting rows
Use the following statement to create the from the trigger table. For example, the following
EmpDeptHistory table: SELECT * INTO statement creates a trigger to disable the deletion of rows
EmpDeptHistory FROM from the Department table:
HumanResources.EmployeeDepartmentHisto CREATE TRIGGER trgDeleteDepartment
ry ON HumanResources.Department
For example, you can execute the following UPDATE FOR DELETE
statement on the EmpDeptHistory table: AS
UPDATE EmpDeptHistory SET DepartmentID PRINT 'Deletion of Department is not
= 16 allowed'
WHERE EmployeeID = 4 ROLLBACK TRANSACTION
When the preceding statement is executed, the trgMagic RETURN
trigger is fired displaying the output, as shown in the Creating an UPDATE Trigger
following figure. An UPDATE trigger gets fired at the time of updating
records in the trigger table. For example, you need to
create a trigger to ensure that the average of the values in
the Rate column of the EmployeePayHistory table should
not be more than 20 when the value of Rate is increased.
To perform this task, you can use the following statement:
CREATE TRIGGER
The Output Derived by Using the UPDATE Statement trgUpdateEmployeePayHistory
In the preceeding figure, the result set on the top shows the ON HumanResources.EmployeePayHistory
values before the execution of the UPDATE statement and FOR UPDATE
the result set at the bottom shows the updated values. AS
IF UPDATE (Rate)
Creating an INSERT Trigger BEGIN
An INSERT trigger gets fired at the time of adding new DECLARE @AvgRate float
rows in the trigger table. For example, users at SELECT @AvgRate = AVG(Rate)
AdventureWorks, Inc. want the modified date to be set to FROM HumanResources.EmployeePayHistory
the current date whenever a new record is entered in the IF(@AvgRate > 20)
Shift table. To perform this task, you can use the following BEGIN
statement: PRINT 'The average value of rate
CREATE TRIGGER cannot be more than 20'
HumanResources.trgInsertShift ROLLBACK TRANSACTION
ON HumanResources.Shift END
FOR INSERT END
AS
DECLARE @ModifiedDate datetime Creating an AFTER Trigger
SELECT @ModifiedDate = ModifiedDate An AFTER trigger gets fired after the execution of a DML
FROM Inserted statement. For example, you need to display a message
IF (@ModifiedDate != getdate()) after a record is deleted from the Employee table. To
BEGIN perform this task, you can write the following statement:
PRINT 'The modified date should be CREATE TRIGGER trgDeleteShift ON
the current date. HumanResources.Shift
AFTER DELETE
AS CREATE TRIGGER trgDelete ON
PRINT 'Deletion successful' Sales.Customer
If there are multiple AFTER triggers for a single DML INSTEAD OF DELETE
operation, you can change the sequence of execution of AS
these triggers by using the sp_settriggerorder system PRINT 'Customer records cannot be
stored procedure. The syntax of the sp_settriggerorder deleted'
stored procedure is: Creating a DDL Trigger
sp_settriggerorder <triggername>, DDL triggers are special kind of triggers that fire in
<order-value>, <DML-operation> response to the DDL statements. They can be used to
where, perform administrative tasks in the database such as
triggername specifies the name of the trigger whose auditing and regulating database operations. The following
order of execution needs to be changed. statement creates a DDL trigger:
order-value specifies the order in which the trigger CREATE TRIGGER safety
needs to be executed. The values that can be entered are ON DATABASE
FIRST, LAST, and NONE. If FIRST is mentioned, then FOR DROP_TABLE, ALTER_TABLE
the trigger is the first trigger to be executed. If LAST is AS
mentioned, then the trigger will be the last trigger to be PRINT 'You must disable Trigger
executed. If NONE is specified, then the trigger is "safety" to drop or alter tables!'
executed on a random basis. ROLLBACK
DML-operation specifies the DML operation for which In the preceding statement, the safety trigger will fire
the trigger was created. This should match the DML whenever a DROP_TABLE or ALTER_TABLE event
operation associated with the trigger. For example, if occurs in the database.
UPDATE is specified for a trigger that is created for the While creating DDL triggers, you need to use DDL events
INSERT operation, the sp_settriggerorder stored that can be used to fire a DDL trigger. Some of the DDL
procedure will generate an error. events that can be used with DDL triggers are:
For example, you have created another AFTER trigger, CREATE_FUNCTION
trgDeleteShift1 on the Shift table, as shown in the ALTER_FUNCTION
following statement: DROP_FUNCTION
CREATE TRIGGER trgDeleteShift1 ON CREATE_INDEX
HumanResources.Shift ALTER_INDEX
AFTER DELETE DROP_INDEX
AS CREATE_PROCEDURE
PRINT 'Attempting to Delete' ALTER_PROCEDURE
By default, triggers are executed in the sequence of their DROP_PROCEDURE
creation. However, if you need to execute the trigger CREATE_SYNONYM
named trgDeleteShift1 before the trgDeleteShift trigger, DROP_SYNONYM
you can execute the following statement: CREATE_TABLE
sp_settriggerorder ALTER_TABLE
'HumanResources.trgDeleteShift1', DROP_TABLE
'FIRST', 'DELETE' CREATE_TRIGGER
RETURN ALTER_TRIGGER
Creating an INSTEAD OF Trigger DROP_TRIGGER
INSTEAD OF triggers are executed in place of the events The events in the preceding list correspond to the SQL
that cause the trigger to fire. For example, if you create an statement, the syntax of which is modified to include
INSTEAD OF UPDATE trigger on a table, the statements underscores ('_') between keywords.
specified in the trigger will be executed instead of the
UPDATE statement that caused the trigger to fire.
These triggers are executed after the inserted table and the
Managing Triggers
deleted table reflecting the changes to the base table are While managing triggers, you can perform the following
created, but before any other action is taken. They are operations on a trigger:
executed before any constraint, and therefore, supplement Alter a trigger
the action performed by a constraint. You can create the Delete a trigger
following INSTEAD OF trigger to restrict the deletion of
records in the Customer table:
Altering a Trigger
As a database developer, you might need to modify the
logic or code behind a trigger. For example, a trigger is
used to calculate a 10 percent discount on every item sold.
With the new management policy, the discount rate has
been increased to 15 percent. To reflect this change in the
trigger, you need to change the code in the trigger. You can
use the ALTER TRIGGER statement to modify the trigger.
The syntax of the ALTER TRIGGER statement is:
ALTER TRIGGER trigger_name
{ FOR | AFTER | INSTEAD OF}
{ event_type [ ,...n ] |
DDL_DATABASE_LEVEL_EVENTS }
{ AS
{ sql_statement [ ...n ] }
}
For example, you can modify the trgDeleteShift trigger
that was created earlier to restrict the deletion of records in
the Shift table. To modify the trgDeleteShift trigger, you
need to execute the following statement: Disabling a Trigger
ALTER TRIGGER Sometimes, you need to prevent the execution of a trigger
HumanResources.trgDeleteShift ON to perform a specific operation on a table. For example, a
HumanResources.Shift trigger is created on the Employee table that prevents the
INSTEAD OF DELETE modification of the employee data. However, one of the
AS employees has shifted to another department. This requires
PRINT 'Deletion of Shift details is you to make the necessary changes in the Employee table.
not allowed' You can perform this task by disabling the trigger.
ROLLBACK TRANSACTION Once the trigger is disabled, it will not execute until it is
RETURN enabled again. Disabling a trigger does not delete the
Apart from altering a DML trigger, you can modify a DDL trigger. It remains in the database, but does not execute in
trigger by executing the following ALTER statement: response to an event.
ALTER TRIGGER safety SQL Server provides the DISABLE TRIGGER statement
ON DATABASE to disable an existing trigger. The syntax of the DISABLE
FOR DROP_TABLE TRIGGER statement is:
AS DISABLE TRIGGER { [ schema_name . ]
PRINT 'YOU CAN ALTER BUT NOT DELETE trigger_name | ALL }
TABLE' ON { object_name | DATABASE }
After executing the preceding statement, the safety trigger where,
is modified for dropping a table. The safety trigger is fired schema_name specifies the name of schema to which
whenever you try to drop any table in the database. the trigger belongs.
Deleting a Trigger trigger_name specifies the name of the trigger to be
As the requirements change, you may need to delete some disabled.
triggers. For example, you have a trigger that updates the All specifies that all triggers defined at the scope of the
salaries of the employees in their pay slips. Now, this ON clause are disabled.
function is performed by a front-end application in your object_name specifies the name of the table, or view
organization. Therefore, you need to remove the trigger. on which the trigger was defined.
To delete a trigger, you can use the DROP TRIGGER DATABASE is used for a DDL trigger.
statement. The syntax of the DROP TRIGGER statement For example, you can disable the safety trigger by
is: executing the following statement:
DROP TRIGGER { trigger } DISABLE TRIGGER safety ON DATABASE
where, Enabling a Trigger
trigger is the name of the trigger you want to drop. You disable the triggers when you do not want them to be
The following statement drops the trgMagic trigger: executed. Later, if you want them to be executed in
DROP TRIGGER trgMagic response to their respective events, you can again enable
them.
SQL Server provides the ENABLE TRIGGER statement
to enable a trigger. The syntax of the ENABLE TRIGGER CommandText)[1]','nvarchar(max)')
statement is: ROLLBACK
ENABLE TRIGGER { [ schema_name . ] In the preceding code, the value() function is used to
trigger_name | ALL } display the data of the CommandText tag. This tag stores
ON { object_name | DATABASE } the actual query that caused the trigger to fire.
For example, you can enable the safety trigger by You can display the event information after executing the
executing the following statement: following CREATE TABLE statement:
ENABLE TRIGGER safety ON DATABASE CREATE TABLE NewTable
Displaying Events of a Trigger (
Sometimes, you want to know the information about the Customer_name varchar(30),
Salary int
events that caused the trigger to be executed. For example,
)
a new payroll software is being installed in an
organization. James, a database developer, wants to After executing the preceding statement, the Info_Event
understand the behavior of the new software under the trigger is fired and the output is displayed, as shown in the
predefined data. He has created a trigger that is fired when following figure.
the database is modified. While executing the trigger, he
wants to get the detailed information, such as the events
that caused the trigger to be fired and the SQL statement
that was executed to fire the trigger.
The Output Derived After Info_Event Trigger Fires
SQL Server provides the EVENTDATA() function that
can be embedded with the CREATE TRIGGER statement
to provide the information, such as time and type of the Using the UPDATE() Function
event that caused the trigger to fire. The EVENTDATA()
function returns the details of the trigger in the XML While performing the UPDATE operation on a database
format. This XML data contains <EVENT_INSTANCE> object, you may need to perform specific actions on
as the parent tag. The sample format of the XML data another database object. To achieve this functionality, you
returned by the EVENTDATA() function is: can use the UPDATE trigger on a database object. The
<EVENT_INSTANCE> scope of the UPDATE trigger is tables. In other words, the
<EventType> </EventType> UPDATE trigger is fired on updating any column of a
<PostTime> </PostTime> table on which the trigger is defined. However, at times,
<SPID> </SPID> you require that the UPDATE trigger should be fired when
<ServerName> </ServerName> a specific column in a table is updated.
<LoginName> </LoginName> For example, in an organization, the employees use the
<UserName> </UserName> Online Leave Approval system to apply for leaves. When
<DatabaseName> </DatabaseName> an employee applies for a leave, the leave details are
<SchemaName> </SchemaName> stored in the LeaveDetails table. In addition, a new record
<ObjectName> </ObjectName> is added to the LeavesForApproval table. When the
<TSQLCommand> supervisors log on to the system, all the leaves pending for
<CommandText> </CommandText> their approval are retrieved from the LeavesForApproval
</TSQLCommand> table and displayed to them. The supervisor approves or
</EVENT_INSTANCE> denies a leave by updating the LeaveStatus column of the
To retrieve the data stored in the preceding XML format, LeavesForApproval table. Therefore, you want that after a
you need to use the functions of the XQuery language. supervisor updates the value of the LeaveStatus column in
For example, you can create a trigger on the the LeavesForApproval table, the LeaveStatus column in
AdventureWorks database with the EVENTDATA() the LeaveDetails table should also be updated.
function by executing the following statement: To achieve the functionality required in the preceding
CREATE TRIGGER Info_Event scenario, you can use the UPDATE() function with an
ON DATABASE UPDATE trigger. SQL Server provides the UPDATE()
FOR CREATE_TABLE function that can be used to create an UPDATE trigger
AS applied to specific columns. The syntax of the UPDATE()
PRINT 'CREATING TABLE' function is:
RAISERROR ('New tables cannot be UPDATE (column)
created in this database.', 16, 1) where,
SELECT EVENTDATA().value('(/
column specifies the name of the column on which an
EVENT_INSTANCE/TSQLCommand/
UPDATE trigger is applied. until one transaction is executed so that only one
For example, you want that whenever an attempt is made transaction can work on a database resource at a time.
to update the VacationHours or Title columns of the
Employee table, a message should be displayed and the
updates should be rolled back. For this, you can create an Creating Transactions
AFTER UPDATE trigger with the UPDATE() function. To
A transaction can be defined as a sequence of operations
accomplish this task, you can use the following statement:
performed together as a single logical unit of work. A
USE AdventureWorks
single unit of work must possess the following properties
GO
called ACID (Atomicity, Consistency, Isolation, and
CREATE TRIGGER reminder
Durability).
ON HumanResources.Employee
AFTER UPDATE Atomicity: This states that either all the data
AS modifications are performed or none of them are
IF (UPDATE (VacationHours) OR UPDATE performed.
(Title)) Consistency: This states that all data is in a
BEGIN consistent state after a transaction is completed
Print 'You cannot update the specified successfully. All rules in a relational database
columns' must be applied to the modifications in a
ROLLBACK TRAN transaction to maintain complete data integrity.
END Isolation: This states that any data modification
GO made by concurrent transactions must be isolated
In the preceding statement, the VacationHours and Title from the modifications made by other concurrent
columns are specified in the UPDATE() function to fire transactions. In simpler words, a transaction
the trigger whenever an attempt is made to update these either accesses data in the state in which it was
columns. before a concurrent transaction modified it or
After creating the trigger, you can use the following accesses the data after the second transaction has
statement to verify the trigger: been completed. There is no scope for the
UPDATE HumanResources.Employee transaction to see an intermediate state.
SET VacationHours=25 Durability: This states that any change in data by
WHERE Employee.EmployeeID=1 a completed transaction remains permanently in
When the preceding statement is executed, the reminder effect in the system. Therefore, any change in
trigger is fired to prevent the updation of the data due to a completed transaction persists even
VacationHours column. in the event of a system failure. This is ensured
by the concept of backing up and restoring
transaction logs.
Activity 8.1: Implementing It is important that a database system provides
mechanisms to ensure the physical integrity of each
Triggers transaction. To fulfill the requirements of the ACID
properties, SQL Server provides the following features:
Transaction management: Ensures the atomicity
Implementing Transactions and consistency of all transactions. A transaction
must be successfully completed after it has started
At times, you are required to execute a sequence of or SQL Server undoes all the data modifications
statements as a single logical unit of work. For example, made since the start of the transaction.
whenever you transfer money from one bank account to Locking: Preserves transaction durability and
another account, the amount is debited from one account isolation.
and credited to another account. In such a situation, you SQL Server allows implementing transactions in the
need either all the statements to be executed successfully following ways:
or none of them to be executed. This helps in ensuring Autocommit transaction
data integrity. Implicit transaction
In SQL Server, you can implement transactions to ensure Explicit transaction
data integrity. In a multi user environment, there can be
multiple transactions accessing the same resource at the Autocommit Transaction
same time. To prevent errors that could occur due to The autocommit transaction is the default transaction
transactions accessing the same resource, you can use management mode of SQL Server. Based on the
locks. Locks provide a mechanism to secure a resource completeness of every T-SQL statement, transactions are
automatically committed or rolled back. A statement is Explicit Transaction
committed if it is completed successfully, and it is rolled An explicit transaction is the one where both the start and
back if it encounters an error. the end of the transaction are defined explicitly. Explicit
Implicit Transaction transactions were called user-defined or user-specified
An implicit transaction is the one where you do not need transactions in earlier versions of SQL Server. They are
to define the start of the transaction. You are only required specified by using the following statements:
to commit or roll back the transaction. You also need to BEGIN TRANSACTION: Is used to set the
turn on the implicit transaction mode to specify the starting point of a transaction.
implicit transaction. After you have turned on the implicit COMMIT TRANSACTION: Is used to save the
transaction mode, SQL Server starts the transaction when changes permanently in the database.
it executes any of the statements listed in the following ROLLBACK TRANSACTION: Is used to undo
table. the changes.
SAVE TRANSACTION: Is used to establish
ALTER TABLE INSERT CREATE save points that allow partial rollback of a
OPEN DELETE DROP transaction.
REVOKE SELECT FETCH
TRUNCATE GRANT UPDATE You can use the BEGIN TRANSACTION statement to
TABLE override the default autocommit mode. SQL Server returns to
the autocommit mode when the explicit transaction is
The Implicit Transaction Statements committed or rolled back.
The transaction remains in effect until you issue a Beginning a Transaction
COMMIT or ROLLBACK statement. After the first The BEGIN TRANSACTION statement marks the start of
transaction is committed or rolled back, SQL Server starts a transaction. The syntax of the BEGIN TRANSACTION
a new transaction the next time any of the preceding statement is:
statements is executed. SQL Server keeps generating a BEGIN TRAN[SACTION] [transaction_name
chain of implicit transactions until you turn off the implicit | @tran_name_variable]
transaction mode. where,
You can turn on the implicit transaction mode by using the transaction_name is the name assigned to the
following statement: transaction. This parameter must conform to the rules for
SET IMPLICIT_TRANSACTIONS ON; identifiers and should not be more than 32 characters.
For example, consider the following statements: @tran_name_variable is the name of a user-defined
SET IMPLICIT_TRANSACTIONS ON; variable that contains a valid transaction name. This
Insert into Depositor (Customer_name, variable must be declared with a char, varchar, nchar, or
Acc_num) values('Nora',101), ('Robin', nvarchar data type.
4101), Commiting a Transaction
('James', 501), ('Jennifer', 7101) The COMMIT TRANSACTION or COMMIT WORK
statement marks the end of an explicit transaction. This
-- Commit first transaction statement is used to end a transaction for which no errors
COMMIT TRANSACTION; were encountered during the transaction. The syntax of the
-- Second implicit transaction started COMMIT TRANSACTION statement is:
by a SELECT statement COMMIT [ TRAN[SACTION]
SELECT COUNT(*) FROM Depositor [transaction_name |
INSERT INTO Depositor VALUES ('Peter', @tran_name_variable] ]
9200)
where,
SELECT * FROM Depositor;
-- Commit second transaction transaction_name specifies a transaction name
COMMIT TRANSACTION; assigned by a previous BEGIN TRANSACTION
In the preceding statements, the implicit transaction mode statement. It can be used to indicate the nested BEGIN
is turned on. After the first transaction is committed, the TRANSACTION statement that is associated with the
second implicit transaction is started as soon as the COMMIT TRANSACTION statement.
SELECT statement is executed. @tran_name_variable is the name of a user-defined
You can turn off the implicit transaction mode by using the variable that contains a valid transaction name. This
following statement: variable must be declared with a char, varchar, nchar, or
SET IMPLICIT_TRANSACTIONS OFF; nvarchar data type.
Consider a scenario where the salary of an employee transaction '+ convert(varchar
named Robert is changed to $15000 and the salary of an (3),@@TRANCOUNT)
employee named Jack is changed to $18000. To perform BEGIN TRAN
these transactions, you need to execute the following PRINT'beginning with the third
statements: transaction ' + convert(varchar
UPDATE EmployeeDetails (3),@@TRANCOUNT)
SET Salary = 15000 COMMIT
WHERE EmpName = 'Robert' PRINT 'commiting the first trasaction
UPDATE EmployeeDetails '+ convert(varchar(3),@@TRANCOUNT)
SET Salary = 18000 COMMIT
WHERE EmpName = 'Jack' PRINT 'commiting the second
When the preceding statements are executed, either both transaction '+ convert(varchar
should be executed successfully or none of them should be (3),@@TRANCOUNT)
executed. If any of the statements fails to execute, the commit
entire transaction should be rolled back. Therefore, you PRINT 'commiting the third transaction
need to define the beginning and end of a transaction, as '+ convert(varchar(3),@@TRANCOUNT)
shown in the following statements: The following figure displays the output of the preceding
BEGIN TRAN myTran statements.
UPDATE EmployeeDetails
SET Salary = 10000
WHERE EmpName = 'Robert'
UPDATE EmployeeDetails
SET Salary = 12000
WHERE EmpName = 'Jack'
COMMIT TRAN myTran
The preceding statements create a transaction named
myTran, which updates the salaries of the employees in
the EmployeeDetails table.
Reference Reading
Implementing Triggers
Reference Reading
Monitoring Performance
Optimizing Performance