SQL
SQL Stored Procedures and Functions
|
Feature |
Stored Procedure |
Function |
|
Purpose |
Used to perform
actions (e.g., insert, update, delete) and can return results. |
Primarily used to
compute and return a single value or a table. |
|
Return Type |
Does not return a
value directly; can return multiple result sets. |
Must return a value
(scalar or table) using the RETURN statement. |
|
Invocation |
Called using
the EXEC or CALL statement. |
Called as part of an
expression, like in a SELECT statement. |
|
Transaction Control |
Can manage
transactions (e.g., BEGIN, COMMIT, ROLLBACK). |
Cannot manage
transactions; they are typically used within a transaction. |
|
Side Effects |
Can have side
effects (e.g., modifying data). |
Should not have side
effects; they are expected to be deterministic. |
|
Parameters |
Can accept input and
output parameters. |
Can accept input
parameters but cannot have output parameters. |
|
Use Cases |
Suitable for complex
operations, batch processing, and business logic. |
Suitable for
calculations, data transformations, and returning values. |
|
Performance |
Generally optimized
for performance in executing complex logic. |
Can be optimized for
use in queries, especially when used in SELECT statements. |
|
Error Handling |
Can use TRY...CATCH for error handling. |
Can use TRY...CATCH, but error handling is limited compared to stored procedures. |
Stored Procedure
CREATE PROCEDURE GetEmployeeDetails
@EmployeeID INT
AS
BEGIN
SELECT *
FROM Employees WHERE EmployeeID = @EmployeeID;
END
Function
CREATE FUNCTION GetEmployeeFullName
(@EmployeeID INT)
RETURNS VARCHAR(100)
AS
BEGIN
DECLARE
@FullName VARCHAR(100);
SELECT
@FullName = FirstName + ' ' + LastName FROM Employees WHERE EmployeeID =
@EmployeeID;
RETURN
@FullName;
END
Calling a Function:
SELECT
dbo.GetEmployeeFullName(1) AS FullName;
A cursor
A cursor in SQL is a database
object used to retrieve, manipulate, and navigate through a result set row by
row. Cursors allow you to process individual rows of a result set, which can be
useful for operations that cannot be done in a single SQL statement, such as
row-by-row processing or handling procedural logic.
Steps to work with a cursor:
- Declare a Cursor: Define
the SQL query whose results will be fetched using the cursor.
- Open the Cursor: Execute
the query and populate the result set.
- Fetch Rows: Retrieve rows
from the cursor one at a time.
- Process Rows: Perform the
required operations on each row.
- Close the Cursor: Release
the cursor once it's no longer needed.
- Deallocate the Cursor:
Remove the cursor from memory.
Example of a Cursor:
DECLARE @PatientID INT, @DoctorName NVARCHAR(100); -- Step 1: Declare the CursorDECLARE PatientCursor CURSOR FORSELECT patient_id, CONCAT(first_name, ' ', last_name)FROM patients; -- Step 2: Open the CursorOPEN PatientCursor; -- Step 3: Fetch the first row into variablesFETCH NEXT FROM PatientCursor INTO @PatientID, @DoctorName; -- Step 4: Loop through the result setWHILE @@FETCH_STATUS = 0BEGIN -- Process each row (e.g., print out patient info) PRINT 'Patient ID: ' + CAST(@PatientID AS NVARCHAR(10)) + ', Doctor: ' + @DoctorName; -- Fetch the next row FETCH NEXT FROM PatientCursor INTO @PatientID, @DoctorName;END; -- Step 5: Close and deallocate the CursorCLOSE PatientCursor;DEALLOCATE PatientCursor;Key Points:
- Cursor Types:
- Static: A snapshot of the
result set, not reflecting changes to the underlying data.
- Dynamic: Reflects changes
in the result set during cursor traversal.
- Forward-only: Can only
move forward through the result set.
- Keyset-driven: Can move
both forward and backward, but the result set is static.
- Performance Considerations:
Cursors can be inefficient for large result sets because they process rows
one at a time. It's often better to use set-based operations in SQL when
possible.
When to Use Cursors:
- When a task
requires row-by-row processing.
- When working
with complex business logic that cannot be expressed using set-based
queries.
- When no
other alternatives (like
WHILEloops orJOINoperations) can achieve the desired result.
Comparison of DELETE and TRUNCATE
|
Feature |
DELETE |
TRUNCATE |
|
Operation
Type |
Removes
rows one by one |
Removes
all rows at once |
|
Where Clause Support |
Yes, can delete specific rows
using WHERE clause |
No, removes all rows without
filtering |
|
Performance |
Slower,
as each row is deleted individually |
Faster,
deallocates entire data pages |
|
Triggers |
Fires triggers (e.g., ON DELETE) |
Does not fire triggers |
|
Transaction
Rollback |
Can
be rolled back if inside a transaction |
Can
be rolled back in some DBMS (if in a transaction) |
|
Identity Column Reset |
Does not reset the identity column |
Resets the identity column to its
seed value |
|
Logging |
Logs
individual row deletions |
Minimal
logging (bulk operation) |
|
Locking |
May acquire row-level or table
lock |
Typically requires a table-level
lock |
|
Speed |
Slower
for large tables due to row-by-row deletion |
Faster,
especially for large tables |
|
Use Case |
When specific rows need to be
deleted, or triggers are needed |
When all rows in a table need to
be removed quickly |
|
Data
Integrity |
Can
be slower for large datasets, may be more resource-intensive |
Efficient
for large datasets but removes all rows without fine control |
|
Resource Usage |
Higher resource consumption for
large tables |
Lower resource consumption for
large tables |
DROP:
- Completely removes a table
(including its structure) from the database.
- Cannot be rolled back (unless
inside a transaction).
- Does not fire triggers.
What are the different types of indexes in
SQL?
· Clustered
Index:
- The
data in the table is stored in the order of the clustered index. A table
can have only one clustered index.
- It’s
typically created automatically for the primary key.
· Non-Clustered
Index:
- A
separate structure from the data table, containing a pointer to the
actual rows. A table can have multiple non-clustered indexes.
· Unique
Index:
- Ensures
that all values in the indexed column(s) are unique.
· Composite
Index:
- An
index on multiple columns, useful for queries involving multiple columns
in the
WHEREclause.
Explain the difference between UNION and UNION ALL.
- UNION:
- Combines
the results of two queries and removes duplicate rows.
- UNION ALL:
- Combines
the results of two queries without removing duplicates.
What is the difference between WHERE and HAVING clauses?
- WHERE:
- Filters
rows before any grouping operation (i.e., before
GROUP BY). - Can
be used on columns in the table.
- HAVING:
- Filters
groups created by
GROUP BY. - Can
be used with aggregate functions.
Comments
Post a Comment