Podcast
Questions and Answers
Which characteristic differentiates TRANSACT-SQL from standard SQL?
Which characteristic differentiates TRANSACT-SQL from standard SQL?
- Standard SQL extends the capabilities of Microsoft SQL Server, while TRANSACT-SQL focuses on basic querying functions.
- TRANSACT-SQL incorporates programming structures, while standard SQL primarily focuses on data querying. (correct)
- TRANSACT-SQL is limited to data querying, while standard SQL handles comprehensive database management.
- Standard SQL is exclusive to Microsoft SQL Server, whereas TRANSACT-SQL is universally compatible.
What distinguishes local variables from global variables in SQL Server?
What distinguishes local variables from global variables in SQL Server?
- Local variables are named starting with '@@', whereas global variables start with '@'.
- Local variables are defined (declared) by the user, while global variables are supplied by the system. (correct)
- Local variables retain their values across different SQL Server sessions, unlike global variables.
- Local variables are predefined by the system, while global variables are defined by the user.
Which statement correctly describes how to assign a value to a local variable using a SELECT statement?
Which statement correctly describes how to assign a value to a local variable using a SELECT statement?
- The SELECT statement, when used for assignment, cannot return values to the client as a result set. (correct)
- Using SELECT for assignment allows assigning values, but it also requires specifying the data type inline with the variable.
- The SELECT statement can return values to the client as a set of results, without assigning them to the variable.
- SELECT for assignment is exclusively used for assigning values to global variables, not local variables.
Which of the following is true regarding global variables in SQL Server?
Which of the following is true regarding global variables in SQL Server?
What is the main function of the @@ERROR
global variable in SQL Server?
What is the main function of the @@ERROR
global variable in SQL Server?
In SQL Server, how can you conditionally execute a block of code?
In SQL Server, how can you conditionally execute a block of code?
What is the primary purpose of the CASE
structure in SQL?
What is the primary purpose of the CASE
structure in SQL?
Which SQL structure is best suited for executing a block of code repeatedly as long as a condition remains true?
Which SQL structure is best suited for executing a block of code repeatedly as long as a condition remains true?
What is the purpose of the BREAK
statement within a WHILE
loop in SQL?
What is the purpose of the BREAK
statement within a WHILE
loop in SQL?
What happens when the CONTINUE
statement is executed inside a WHILE
loop?
What happens when the CONTINUE
statement is executed inside a WHILE
loop?
What does the RETURN [n]
statement do in a SQL stored procedure?
What does the RETURN [n]
statement do in a SQL stored procedure?
What is the primary use of the TRY...CATCH
block in SQL Server?
What is the primary use of the TRY...CATCH
block in SQL Server?
In a TRY...CATCH
block, when is the code inside the CATCH
block executed?
In a TRY...CATCH
block, when is the code inside the CATCH
block executed?
Which function in SQL Server returns the error message within a CATCH
block?
Which function in SQL Server returns the error message within a CATCH
block?
What does the ERROR_SEVERITY()
function provide in a SQL Server CATCH
block?
What does the ERROR_SEVERITY()
function provide in a SQL Server CATCH
block?
Which of the following is the purpose of the function ERROR_PROCEDURE()
in SQL Server error handling?
Which of the following is the purpose of the function ERROR_PROCEDURE()
in SQL Server error handling?
In Transact-SQL, what is the purpose of the RAISERROR
function?
In Transact-SQL, what is the purpose of the RAISERROR
function?
Which of the following statements is true regarding the severity levels that you can assign with the RAISERROR function without being a member of the sysadmin fixed server role?
Which of the following statements is true regarding the severity levels that you can assign with the RAISERROR function without being a member of the sysadmin fixed server role?
What is the purpose of a cursor in Transact-SQL?
What is the purpose of a cursor in Transact-SQL?
Which step is NOT part of the standard cursor operations in Transact-SQL?
Which step is NOT part of the standard cursor operations in Transact-SQL?
Which statement is used to move to the next row in a cursor?
Which statement is used to move to the next row in a cursor?
Assume a cursor has been opened and processed. What is the purpose of the CLOSE
statement concerning the cursor?
Assume a cursor has been opened and processed. What is the purpose of the CLOSE
statement concerning the cursor?
After using the CLOSE
statement on a cursor, which statement completely releases all resources associated with the cursor, including its definition?
After using the CLOSE
statement on a cursor, which statement completely releases all resources associated with the cursor, including its definition?
Which cursor type allows you to move only forward through the result set?
Which cursor type allows you to move only forward through the result set?
Which cursor type reflects all data changes as they occur in the database?
Which cursor type reflects all data changes as they occur in the database?
What does the INSENSITIVE
keyword do when declaring a cursor?
What does the INSENSITIVE
keyword do when declaring a cursor?
If a cursor is declared with the READ_ONLY
option, what does this imply for operations using that cursor?
If a cursor is declared with the READ_ONLY
option, what does this imply for operations using that cursor?
What is the purpose of using SCROLL_LOCKS
in a cursor declaration?
What is the purpose of using SCROLL_LOCKS
in a cursor declaration?
What does @@FETCH_STATUS
indicate after a FETCH
statement is executed?
What does @@FETCH_STATUS
indicate after a FETCH
statement is executed?
Flashcards
What is SQL?
What is SQL?
SQL is a query language for relational database systems.
What are local variables?
What are local variables?
Variables that are defined by the user in SQL Server.
What are global variables?
What are global variables?
Variables in SQL Server supplied by the system and are predefined.
What is the 'declare' keyword?
What is the 'declare' keyword?
Signup and view all the flashcards
What is the '@' symbol?
What is the '@' symbol?
Signup and view all the flashcards
What is the SELECT assignment?
What is the SELECT assignment?
Signup and view all the flashcards
What are global variables indicated by?
What are global variables indicated by?
Signup and view all the flashcards
What is @@ERROR?
What is @@ERROR?
Signup and view all the flashcards
What is @@IDENTITY?
What is @@IDENTITY?
Signup and view all the flashcards
What is @@VERSION?
What is @@VERSION?
Signup and view all the flashcards
What is the function of 'IF...ELSE'?
What is the function of 'IF...ELSE'?
Signup and view all the flashcards
What is the 'CASE' structure?
What is the 'CASE' structure?
Signup and view all the flashcards
What is the 'WHILE' structure?
What is the 'WHILE' structure?
Signup and view all the flashcards
What does 'BREAK' do?
What does 'BREAK' do?
Signup and view all the flashcards
What does 'CONTINUE' do?
What does 'CONTINUE' do?
Signup and view all the flashcards
What does 'RETURN [n]' do?
What does 'RETURN [n]' do?
Signup and view all the flashcards
What does 'PRINT' do?
What does 'PRINT' do?
Signup and view all the flashcards
What is the 'CASE' expression?
What is the 'CASE' expression?
Signup and view all the flashcards
What is the 'WHILE' control structure?
What is the 'WHILE' control structure?
Signup and view all the flashcards
How are errors controlled in Transact-SQL?
How are errors controlled in Transact-SQL?
Signup and view all the flashcards
What are special error functions?
What are special error functions?
Signup and view all the flashcards
What does ERROR_NUMBER() do?
What does ERROR_NUMBER() do?
Signup and view all the flashcards
What is ERROR_SEVERITY()?
What is ERROR_SEVERITY()?
Signup and view all the flashcards
What is the 'variable @@ERROR'?
What is the 'variable @@ERROR'?
Signup and view all the flashcards
What is RAISERROR?
What is RAISERROR?
Signup and view all the flashcards
What is a cursor?
What is a cursor?
Signup and view all the flashcards
What does 'DECLARE <cursor_name> CURSOR' do?
What does 'DECLARE <cursor_name> CURSOR' do?
Signup and view all the flashcards
What does 'OPEN <cursor_name>' do?
What does 'OPEN <cursor_name>' do?
Signup and view all the flashcards
What does 'FETCH' in cursors do?
What does 'FETCH' in cursors do?
Signup and view all the flashcards
What does CLOSE do to a cursor?
What does CLOSE do to a cursor?
Signup and view all the flashcards
Study Notes
- SQL is a query language for relational database systems but lacks the power of programming languages
- SQL does not allow use of variables, flow control structures, loops, etc.
- SQL is ideal for working with databases and an additional tool is required for full application development that supports both SQL queries and the versatility of traditional programming languages
- TRANSACT-SQL is a programming language provided by Microsoft SQL Server to extend standard SQL with additional instructions and language-specific elements
TRANSACT-SQL Programming Construction
- TRANSACT-SQL expands standard SQL by implementing programming structures
- Programmers with experience in C++, Java, Visual Basic .NET, C#, and similar languages will find these implementations familiar
Variables
- A variable is an entity to which a value is assigned which can change during the process where the variable is used
- SQL Server has two variable types: local and global
- Local variables are defined by the user
- Global variables are supplied and predefined by the system
Local Variables
- Local variables are declared, named, and written using the keyword
declare
- An initial value is assigned via a
select
orset
instruction - The names of local variables must begin with the “@” symbol
- Each local variable must be assigned a data type defined by the user or supplied by the system
- Syntax to declare a variable:
DECLARE @VARIABLE <DATA TYPE>
to assign a value to a variableSET @VARIABLE= VALUE
- A
SELECT
instruction can be used instead ofSET
- A
SELECT
instruction used to assign values to one or more variables is called an assignmentSELECT
- When using assignment
SELECT
, it cannot return values to the client as a set of results
Public Variables
- Global variables are predefined variables supplied by the system, distinguished from local variables by having two “@” symbols
- Some server global variables include:
@@ERROR
: Contains 0 if the last transaction was executed correctly@@IDENTITY
: Contains the last value inserted into an IDENTITY column through an insert instruction@@VERSION
: Returns the SQL Server version@@SERVERNAME
: Returns the server name@@LANGUAGE
: Returns the language name in use@@MAX_CONNECTIONS
: Returns the maximum number of allowed connections
Flow control tools
- Flow control languages may be used with interactive statements in batches and stored procedures
- Flow control and related keywords and functions include:
IF ... ELSE
: Defines conditional execution if the condition is true or an alternative if the condition is falseCASE
: A simple way to make If-type operationsWHILE
: Repetitive structure that executes a block of instructions while the condition is trueBEGIN ... END
: Defines a block of instructions, that executes a set of instructionsDECLARE
: Declares local variablesBREAK
: Exits the end of the nearest inner while loop...CONTINUE
: Restarts the while loopRETURN [n]
: Unconditionally exits often used in stored or triggered proceduresPRINT
: Prints a user-defined message or a local variable on the user’s screen/*COMMENT*/
orSQL – COMMENT
: Inserts a comment at any point in an SQL instruction
IF Control Structures
- The
IF
keyword is used to define a condition that determines whether the next instruction will be executed - The SQL instruction is executed if the condition is met, i.e. if it returns
TRUE
- The
ELSE
keyword introduces an alternative SQL instruction that executes when theIF
condition returnsFALSE
Conditional CASE Structure
- The
CASE
structure evaluates a list of conditions and returns one of several possible result expressions with two formats:- Simple CASE-expression: Compares an expression with a set of simple expressions to determine the result
- Searched CASE-expression: Evaluates a set of Boolean expressions to determine the result
- Both formats accept an optional
ELSE
argument CASE <expression> WHEN <expression_value> THEN <returned_value> WHEN <expression_value1> THEN <returned_value1> ELSE <returned_value2> END
- The
CASE
structure can be used in any instruction/clause allowing a valid expression such asSELECT
,UPDATE
,DELETE
, andSET
instructions, andselect_list
,IN
,WHERE
,ORDER BY
, andHAVING
clauses - The
CASE
function is a special Transact-SQL expression for showing an alternative value depending on a column
Search CASE Expression
- The search
CASE
expression in aSELECT
instruction allows substituting values in the result set based on comparison values
WHILE Control Structure
- The
WHILE
structure repetitively executes a set/block of SQL instructions as long as the specified condition is true - Execution of instructions in the
WHILE
loop can be controlled with theBREAK
andCONTINUE
keywords - The syntax of
WHILE
is:WHILE <expression> BEGIN ... END
BREAK and CONTINUE
BREAK
andCONTINUE
control the functioning of instructions within aWHILE
loopBREAK
allows exiting theWHILE
loopCONTINUE
causes theWHILE
loop to start again- Syntax for
BREAK
andCONTINUE
:WHILE BOOLEAN_EXPRESSION BEGIN EXPRESSION_SQL [BREAK] [EXPRESSION_SQL] END [CONTINUE] [EXPRESSION_SQL]
Error Control in TRANSACT-SQL
- SQL Server provides error control through
TRY
andCATCH
instructions which mark a step forward in SQL Server error control with syntax:BEGIN TRY EXPRESSION_SQL END TRY BEGIN CATCH EXPRESSION_SQL END CATCH
Special Error Handling Functions
- Special error functions are exclusively available in the
CATCH
block to obtain detailed error information - Functions used in error control include:
ERROR_NUMBER()
: Returns the error numberERROR_SEVERITY()
: Returns the error severityERROR_STATE()
: Returns the error stateERROR_PROCEDURE()
: Returns the stored procedure name that caused the errorERROR_LINE()
: Returns the line number where the error occurredERROR_MESSAGE()
: Returns the error message
System Variable @@ERROR
@@ERROR
returns the last executed TRANSACT-SQL instruction’s error number- If the variable returns 0, the prior TRANSACT-SQL found no errors
- If the error can be found on the
sys.sysmessages
catalog view,@@ERROR
will contain thesys.sysmessages.error
column’s value for said error - The text associated with the error number can be viewed in
sys.sysmessages.description
RAISERROR to Generate Errors
- An error may be voluntarily triggered when the data fails to comply with a business rule
- The
RAISERROR
function receives three parameters: the error message, the severity, and the state - Severity indicates the error’s degree of criticality, admitting values from 0 to 25
- Values from 0 to 18 may be assigned
- Values from 20 to 25 are considered fatal by the system and will close the connection executing the
RAISERROR
command - Assigning values from 19 to 25 requires being a member of the SQL Server
sysadmin
function
Cursors in TRANSACT-SQL
- A cursor is a variable that loops through a result set obtained through a
SELECT
statement row by row - Using cursors is a technique that handles query results row by row, unlike
SELECT
SQL, which handles a set of rows - Cursors can be implemented through TRANSACT-SQL instructions (ANSI-SQL cursors) or the OLE-DB API
- ANSI cursors are used when it is necessary to handle the rows individually in a set or when SQL can only act on the affected rows
- API cursors are used by client applications for handling significant volumes or managing various result sets
- Best practice steps when using cursors:
- Declare the cursor, using
DECLARE
- Open the cursor, using
OPEN
- Read the cursor's data, using
FETCH ... INTO
- Close the cursor, using
CLOSE
- Free the cursor, using
DEALLOCATE
- Declare the cursor, using
Cursor Operations
- Declaration:
DECLARE <CURSOR_NAME> CURSOR FOR <SQL_STATEMENT>
- Opening the cursor:
OPEN <CURSOR_NAME>
- Retrieving the first row of the cursor
- Syntax for syntax to define the declaration of the ANSI cursor:
DECLARE <CURSOR_NAME> [INSENSITIVE][SCROLL] CURSOR FOR <SQL_STATEMENT> FOR [READ ONLY | UPDATE[OF COLUMN_LIST]]
INSENSITIVE
: Only operations on the next row are allowedSCROLL
: movement in cursor rows can be done in all directionsUPDATE
: Specifies that updates are made on the cursor's source table
- The TRANSACT-SQL proposes extended syntax to define cursors:
DECLARE <cursor_name> [LOCAL | GLOBAL]
LOCAL
: the cursor’s scope is local to the whole batchGLOBAL
: The cursor’s scope is global to the connection- By default
to local cursor
database option is defined as false
- Extraction of data from cursor based of the order of appearance is done through
FOWARD_ONLY
- Creation of a temporary copy of the data in the data base for the cursor is done through
STATIC
KEYSET
sets the rows and their order in the cursor at the time of the cursor’s openingDYNAMIC
means the cursor exactly reflects the database's present data: the number of rows, their order, and their value may vary dynamically- You can define a Forward Only cursor through
FAST_FORWARD
- Guarantee the success of
UPDATE
andDELETE
instructions throughSCROLL_LOCKS
OPTIMISTIC
means, anUPDATE
orDELETE
operation performed on the cursor may not be correctly executed, should another transaction modify the data in parallelTYPE_WARNING
sends a client application a warning message should implicit type conversions take place- Opening an cursor requires
OPEN [GLOBAL ] <cursor_name>
Registering Cursors
-
FETCH
extracts a row from the cursor and assigns values to variables with its content - After
FETCH
, the@@FETCH_STATUS
variable is set to 0 ifFETCH
returns no errors FETCH [NEXT | PRIOR | LAST | ABSOLUTE n | RELATIVE n ][FROM] [GLOBAL ] <cursor_name>
NEXT
: reads the next row (The only possible option for INSENSITIVE CURSOR)PRIOR
: Reads the previous lineFIRST
: Reads the first rowLAST
: Reads the last rowABSOLUTE n
: Reads the nth row of the setRELATIVE n
: Reads the nth row from the current row
Cursor Functions
- The
@@FETCH_STATUS
function indicates the status of the last issuedFETCH
instruction; possible values include:- 0: The
FETCH
instruction was successfully executed - -1: The
FETCH
instruction was not successfully executed or the row was beyond the result set - -2: The retrieved row is missing
- 0: The
- Closing the Cursor: Closes the cursor and frees the memory
- This operation should be interposed as soon as possible to free resources sooner
- Syntax for closing the cursor:
CLOSE <cursor_name>
- Once the cursor is closed, it can no longer be captured or updated/eliminated
- All keys are removed when closing the cursor, leaving the cursor definition intact and the closed cursor can be reopened without being re-declared
- Freeing Resources: A cleanup command that is not part of the ANSI specification with syntax:
DEALLOCATE <cursor_name>
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.