C2-Implement error handling and transactions Flashcards
What is TRY…CATCH and what are some of its remarks?
DEF-Implements error handling for Transact-SQL.
Remarks:
The CATCH Block is not always executed, if there is no error in the code it won’t be executed;
The TRY…CATCH must be contained within a single batch. You cannot span more than one BEGIN….END block.
TRY..CATCH blocks are not allowed within functions. Error handling needs to be placed in the code that calls the function, not within the function itself.
What is @@ERROR and how would you use it?
The @@ERROR system function returns 0 if the last Transact-SQL statement executed successfully; if the statement generated an error, @@ERROR returns the error number.
Because @@ERROR gets a new value when every Transact-SQL statement completes, process @@ERROR in one of two ways:
- Test or use @@ERROR immediately after the Transact-SQL statement.
- Save @@ERROR in an integer variable immediately after the Transact-SQL statement completes. The value of the variable can be used later.
What is BEGIN TRANSACTION and what is it’s syntax?
Marks the starting point of an explicit, local transaction. Explicit transactions start with the BEGIN TRANSACTION statement and end with the COMMIT or ROLLBACK statement.
Syntax:
BEGIN { TRAN | TRANSACTION } [;]
or
BEGIN { TRAN | TRANSACTION } [ { transaction_name | @tran_name_variable }
[WITH MARK [ ‘description’] ] ] [;]
What is COMMIT TRANSACTION (Transact-SQL) and what is it’s syntax?
Marks the end of a successful implicit or explicit transaction. If @@TRANCOUNT is 1, COMMIT TRANSACTION makes all data modifications since the start of the transaction a permanent part of the database, frees the transaction’s resources, and decrements @@TRANCOUNT to 0. When @@TRANCOUNT is greater than 1, COMMIT TRANSACTION decrements @@TRANCOUNT only by 1 and the transaction stays active.
syntax:
COMMIT [{ TRAN | TRANSACTION } [ transaction_name | @tran_name_variable] ] [WITH ( DELAYED_DURABILITY = { OFF | ON } )] [;]
SAVE TRANSACTION def, syntax, remarks
def: Sets a savepoint within a transaction.
syntax: SAVE { TRAN | TRANSACTION } { savepoint_name | @savepoint_variable } [;] ;
remarks MSFT:
- A user can set a savepoint, or marker, within a transaction. The savepoint defines a location to which a transaction can return if part of the transaction is conditionally canceled. If a transaction is rolled back to a savepoint, it must proceed to completion with more Transact-SQL statements if needed and a COMMIT TRANSACTION statement, or it must be canceled altogether by rolling the transaction back to its beginning. To cancel an entire transaction, use the form ROLLBACK TRANSACTION transaction_name. All the statements or procedures of the transaction are undone.
- Duplicate savepoint names are allowed in a transaction, but a ROLLBACK TRANSACTION statement that specifies the savepoint name will only roll the transaction back to the most recent SAVE TRANSACTION using that name.
- SAVE TRANSACTION is not supported in distributed transactions started either explicitly with BEGIN DISTRIBUTED TRANSACTION or escalated from a local transaction.
Remarks Mindhub:
- This saves a specific point in the transaction, and there is no corresponding ROLLBACK in the saved point.
- You cannot use SAVETRANSACTION outside of an active transaction.
- There is no value to using SAVE TRANSACTION within a CATCH block.
What is SET NOCOUNT (TRANSACT SQL);
This statement tells SQL SERVER to omit counting the rows processed. The difference in performance would be extremely small, but it will tend to increase the processing time, not to decrease it.
What is THROW(Transact-SQL), what is it’s syntax and remarks?
DEF: Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server 2019;
syntax: THROW
[ { error_number | @local_variable }, —(50000-2147483647)-user defined errors
{ message | @local_variable },
{ state | @local_variable } ] —(0-255)
Remarks:
- The statement before the THROW statement must be followed by the semicolon (;) statement terminator.
- If a TRY…CATCH construct is not available, the statement batch is terminated. The line number and procedure where the exception is raised are set. The severity is set to 16.
- For error handling any new code should use THROW;
- Does not transfer processing to the TRY block but to the CATCH block;
- If THROW does not have any parameters it must be used within a CATCH block.
- Without parameters, THROW re-raises the same error that caused control to be given to the catch block;
RAISERROR-DEF, syntax, remarks
DEF:Generates an error message and initiates error processing for the session. RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct. New applications should use THROW instead.
syntaxsql:
RAISERROR ( { msg_id | msg_str | @local_variable } { ,severity ,state } [,argument [ ,…n] ] )
[WITH option [ ,…n] ]
Remarks:
- Should not be used when writing new code;
- Cannot be used to raise system errors. System errors have error numbers less than 50000
- Always requires parameters
SCOPE IDENTITY: DEF, syntax, remarks
DEF: Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, if two statements are in the same stored procedure, function, or batch, they are in the same scope.
Syntax: SCOPE_IDENTITY()
Remarks:
- SCOPE_IDENTITY, IDENT_CURRENT, and @@IDENTITY are similar functions because they return values that are inserted into identity columns.
- IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT (Transact-SQL).
- SCOPE_IDENTITY and @@IDENTITY return the last identity values that are generated in any table in the current session. However, SCOPE_IDENTITY returns values inserted only within the current scope; @@IDENTITY is not limited to a specific scope.
IDENT_CURRENT-DEF, syntax, remarks
DEF: Returns the last identity value generated for a specified table or view. The last identity value generated can be for any session and any scope.
IDENT_CURRENT( ‘table_or_view’ )
Remarks:
IDENT_CURRENT is similar to the SQL Server 2000 (8.x) identity functions SCOPE_IDENTITY and @@IDENTITY. All three functions return last-generated identity values. However, the scope and session on which last is defined in each of these functions differ:
IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope.
@@IDENTITY returns the last identity value generated for any table in the current session, across all scopes.
SCOPE_IDENTITY returns the last identity value generated for any table in the current session and the current scope.
When the IDENT_CURRENT value is NULL (because the table has never contained rows or has been truncated), the IDENT_CURRENT function returns the seed value.
@@IDENTITY-def, syntax, remarks
def: Is a system function that returns the last-inserted identity value.
syntax: @@IDENTITY
remarks:
After an INSERT, SELECT INTO, or bulk copy statement is completed, @@IDENTITY contains the last identity value that is generated by the statement. If the statement did not affect any tables with identity columns, @@IDENTITY returns NULL. If multiple rows are inserted, generating multiple identity values, @@IDENTITY returns the last identity value generated. If the statement fires one or more triggers that perform inserts that generate identity values, calling @@IDENTITY immediately after the statement returns the last identity value generated by the triggers. If a trigger is fired after an insert action on a table that has an identity column, and the trigger inserts into another table that does not have an identity column, @@IDENTITY returns the identity value of the first insert. The @@IDENTITY value does not revert to a previous setting if the INSERT or SELECT INTO statement or bulk copy fails, or if the transaction is rolled back.
Basiclly it Returns the last identity value inserted into an identity column anywhere in the system.
CREATE TABLE IDENTITY
def: Creates an identity column in a table. This property is used with the CREATE TABLE and ALTER TABLE Transact-SQL statements.
syntaxsql: IDENTITY [(seed , increment)]
remarks:
Identity columns can be used for generating key values. The identity property on a column guarantees the following:
Each new value is generated based on the current seed & increment.
Each new value for a particular transaction is different from other concurrent transactions on the table.
The identity property on a column does not guarantee the following:
- Uniqueness of the value - Uniqueness must be enforced by using a PRIMARY KEY or UNIQUE constraint or UNIQUE index;
- Consecutive values within a transaction - A transaction inserting multiple rows is not guaranteed to get consecutive values for the rows because other concurrent inserts might occur on the table. If values must be consecutive then the transaction should use an exclusive lock on the table or use the SERIALIZABLE isolation level;
- Consecutive values after server restart or other failures -SQL Server might cache identity values for performance reasons and some of the assigned values can be lost during a database failure or server restart. This can result in gaps in the identity value upon insert. If gaps are not acceptable then the application should use its own mechanism to generate key values. Using a sequence generator with the NOCACHE option can limit the gaps to transactions that are never committed;
- Reuse of values - For a given identity property with specific seed/increment, the identity values are not reused by the engine. If a particular insert statement fails or if the insert statement is rolled back then the consumed identity values are lost and will not be generated again. This can result in gaps when the subsequent identity values are generated.
What is FORMATMESSAGE?
Constructs a message from an existing message in sys.messages or from a provided string. The functionality of FORMATMESSAGE resembles that of the RAISERROR statement. However, RAISERROR prints the message immediately, while FORMATMESSAGE returns the formatted message for further processing.
FORMATMESSAGE takes either a message number or a message string. The message string can take a number of parameter values.
- Error number: %u(unsigned integer)
- Error reason: %s(string)
- EX:FORMATMESSAGE(N’Cannot insert customer. Error reason: %s. Error number: %u’, ERROR_MESSAGE(), ERROR_NUMER())
What is nesting transactions?
Explicit transactions can be nested. This is primarily intended to support transactions in stored procedures that can be called either from a process already in a transaction or from processes that have no active transaction.
The following example shows the intended use of nested transactions. The procedure TransProc enforces its transaction regardless of the transaction mode of any process that executes it.
Committing inner transactions is ignored by the SQL Server Database Engine. The transaction is either committed or rolled back based on the action taken at the end of the outermost transaction. If the outer transaction is committed, the inner nested transactions are also committed. If the outer transaction is rolled back, then all inner transactions are also rolled back, regardless of whether or not the inner transactions were individually committed.
Error Message def, syntax, remarks
def: Returns the message text of the error that caused the CATCH block of a TRY…CATCH construct to be run.
syntax: ERROR_MESSAGE may be called anywhere within the scope of a CATCH block;
remarks:
- ERROR_MESSAGE may be called anywhere within the scope of a CATCH block.
- ERROR_MESSAGE returns the error message regardless of how many times it is run, or where it is run within the scope of the CATCH block. This is in contrast to functions like @@ERROR, which only returns an error number in the statement immediately after the one that causes an error, or the first statement of a CATCH block.
- In nested CATCH blocks, ERROR_MESSAGE returns the error message specific to the scope of the CATCH block in which it is referenced. For example, the CATCH block of an outer TRY…CATCH construct could have a nested TRY…CATCH construct. Within the nested CATCH block, ERROR_MESSAGE returns the message from the error that invoked the nested CATCH block. If ERROR_MESSAGE is run in the outer CATCH block, it returns the message from the error that invoked that CATCH block.