{"id":24680952,"url":"https://github.com/drisskhattabi6/sql-server-and-t-sql-lab","last_synced_at":"2026-05-16T21:07:31.210Z","repository":{"id":244282273,"uuid":"812638995","full_name":"drisskhattabi6/SQL-Server-and-T-SQL-Lab","owner":"drisskhattabi6","description":"this repo contains Lab about SQL-Server and T-SQL in French","archived":false,"fork":false,"pushed_at":"2024-06-13T16:47:13.000Z","size":1872,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-21T01:36:58.592Z","etag":null,"topics":["database","lesson","pratical-work","sql","sql-server","t-sql"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/drisskhattabi6.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-06-09T13:15:32.000Z","updated_at":"2025-06-12T03:07:26.000Z","dependencies_parsed_at":"2024-06-13T21:14:04.712Z","dependency_job_id":null,"html_url":"https://github.com/drisskhattabi6/SQL-Server-and-T-SQL-Lab","commit_stats":null,"previous_names":["drisskhattabi6/sql-server-and-t-sql","drisskhattabi6/sql-server-and-t-sql-lab"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/drisskhattabi6/SQL-Server-and-T-SQL-Lab","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/drisskhattabi6%2FSQL-Server-and-T-SQL-Lab","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/drisskhattabi6%2FSQL-Server-and-T-SQL-Lab/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/drisskhattabi6%2FSQL-Server-and-T-SQL-Lab/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/drisskhattabi6%2FSQL-Server-and-T-SQL-Lab/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/drisskhattabi6","download_url":"https://codeload.github.com/drisskhattabi6/SQL-Server-and-T-SQL-Lab/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/drisskhattabi6%2FSQL-Server-and-T-SQL-Lab/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33118969,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-16T18:38:32.183Z","status":"ssl_error","status_checked_at":"2026-05-16T18:38:29.903Z","response_time":115,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","lesson","pratical-work","sql","sql-server","t-sql"],"created_at":"2025-01-26T14:45:53.070Z","updated_at":"2026-05-16T21:07:31.182Z","avatar_url":"https://github.com/drisskhattabi6.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# SQL Server and T-SQL\n\nThis repo contains lesson about SQL-Server and T-SQL with a practical work in French for T-SQL.\n\n- `TD BD2 (T-SQL).pdf` : this pdf contains the questions and exercices.\n- `Rapport.pdf` : this pdf contains the answers and solution of `TD BD2 (T-SQL).pdf`.\n\n---\n\n### Module 1: Introduction to SQL Server\n\n#### 1. Introduction to Databases\n\n- **What is a database?** : Definition: A database is a structured collection of data that can be easily accessed, managed, and updated.\n\n- **Types of databases**\n  - **Relational Databases:**\n    - Structure: Tables, rows, and columns.\n    - Examples: SQL Server, MySQL, PostgreSQL, Oracle Database.\n  - **Non-Relational (NoSQL) Databases:**\n    - Structure: Document, key-value, wide-column, graph.\n    - Examples: MongoDB, Cassandra, Redis.\n  - **In-Memory Databases:**\n    - Usage: Fast data processing, real-time applications.\n    - Examples: Redis, Memcached.\n  - **Cloud Databases:**\n    - Deployment: Managed services in the cloud.\n    - Examples: Amazon RDS, Google Cloud SQL, Azure SQL Database.\n\n- **Introduction to SQL Server**\n  - Overview: SQL Server is a relational database management system (RDBMS) developed by Microsoft.\n  - Key Features: Data storage, querying, security, data integration, business intelligence.\n  - Editions: Express, Standard, Enterprise, Developer.\n\n#### 2. SQL Server Architecture\n\n- **SQL Server components**\n  - **Database Engine:**\n    - Core service for storing, processing, and securing data.\n    - Supports transaction processing, data warehousing, and analytics.\n  - **SQL Server Agent:**\n    - Job scheduling and automation.\n    - Execute scheduled tasks (backups, maintenance).\n  - **SQL Server Integration Services (SSIS):**\n    - Data integration and ETL (Extract, Transform, Load).\n    - Import and export data between different sources.\n  - **SQL Server Reporting Services (SSRS):**\n    - Design, deploy, and manage reports.\n    - Interactive and printed reports.\n  - **SQL Server Analysis Services (SSAS):**\n    - Online Analytical Processing (OLAP) and data mining.\n    - Create and manage multidimensional models.\n\n- **SQL Server services**\n  - **SQL Server Database Engine Service:**\n    - Handles database operations (queries, transactions).\n    - Installed as a Windows service.\n  - **SQL Server Agent Service:**\n    - Manages scheduled jobs.\n    - Essential for automation tasks.\n  - **SQL Server Browser Service:**\n    - Helps clients connect to the correct instance of SQL Server.\n    - Manages instance discovery and connection redirection.\n  - **SQL Server Integration Services (SSIS) Service:**\n    - Executes and manages SSIS packages.\n  - **SQL Server Reporting Services (SSRS) Service:**\n    - Manages report server functions.\n\n- **Database files and filegroups**\n  - **Database Files:**\n    - **Primary Data File (.mdf):** Contains the startup information and the main data.\n    - **Secondary Data Files (.ndf):** Optional, used to spread data across multiple files.\n    - **Transaction Log File (.ldf):** Records all transactions and database modifications.\n  - **Filegroups:**\n    - Logical grouping of data files.\n    - Primary Filegroup: Contains the primary data file and any secondary files not assigned to other filegroups.\n    - User-defined Filegroups: Created for managing data and optimizing performance.\n\n---\n\n### Module 2: SQL Basics\n\n#### 1. Introduction to T-SQL\n\n**Transact-SQL (T-SQL) Definition:**\n\nTransact-SQL, commonly known as T-SQL, is an extension of SQL (Structured Query Language) used primarily with Microsoft SQL Server and Sybase ASE (Adaptive Server Enterprise). T-SQL adds procedural programming capabilities to SQL, allowing for more complex and robust database manipulation and management. These capabilities include control-of-flow constructs (such as IF, WHILE), error handling, and support for variables, along with enhanced functions for string and date manipulation.\n\n**Key Features of T-SQL:**\n\n1. **Procedural Programming Constructs:**\n    - **Control-of-Flow:** Includes statements like `IF...ELSE`, `WHILE`, and `BEGIN...END` for controlling the flow of execution.\n    - **Error Handling:** Uses `TRY...CATCH` blocks to handle errors gracefully within code blocks.\n    - **Variables:** Supports declaring and using variables to store temporary data.\n\n2. **Enhanced Functions:**\n   - **String Functions:** Functions like `CHARINDEX`, `PATINDEX`, `LEN`, `SUBSTRING`, and more for detailed string manipulation.\n   - **Date Functions:** Functions like `GETDATE`, `DATEADD`, `DATEDIFF`, and `FORMAT` for handling date and time values.\n\n3. **Stored Procedures and Functions:**\n    - **Stored Procedures:** Precompiled collections of SQL statements that can accept parameters and be executed as a single unit.\n    - **User-Defined Functions (UDFs):** Custom functions created by users to perform calculations or data transformations, returning either scalar values or tables.\n\n4. **Triggers:**\n    - Special types of stored procedures that automatically execute in response to certain events (INSERT, UPDATE, DELETE) on a table or view.\n\n5. **Common Table Expressions (CTEs):**\n    - Temporary result sets that can be referenced within a `SELECT`, `INSERT`, `UPDATE`, or `DELETE` statement, simplifying complex queries and enabling recursive queries.\n\n6. **Window Functions:**\n\n    - Functions that perform calculations across a set of table rows related to the current row without collapsing the result set, useful for ranking, running totals, and other analytical operations.\n\n**Goal of T-SQL:**\n    To provide a powerful and flexible scripting environment for SQL Server, enabling developers and database administrators to perform complex data manipulation, transaction management, and procedural logic within their databases. T-SQL extends the capabilities of standard SQL, making it a robust tool for managing and querying relational databases efficiently.\n\n## **the different types of variables in T-SQL**\n\nIn Transact-SQL (T-SQL), variables can be categorized into different types based on their scope, usage, and functionality. Here are the different types of variables in T-SQL:\n\n### 1. Scalar Variables\n\n**Definition:** Scalar variables are used to store a single data value of a specific type, such as an integer, a string, a date, etc.\n\n**Common Data Types:**\n\n- **INT:** Stores integer values.\n- **FLOAT:** Stores floating-point numbers.\n- **DECIMAL:** Stores fixed precision and scale numbers.\n- **MONEY:** Stores currency values.\n- **CHAR / VARCHAR:** Stores fixed or variable-length strings.\n- **NCHAR / NVARCHAR:** Stores Unicode strings.\n- **DATETIME:** Stores date and time values.\n- **BIT:** Stores Boolean values (0 or 1).\n\n**Example:**\n\n```sql\nDECLARE @EmployeeID INT;\nDECLARE @EmployeeName NVARCHAR(50);\nDECLARE @HireDate DATETIME;\nDECLARE @IsActive BIT;\n\nSET @EmployeeID = 1;\nSET @EmployeeName = 'John Doe';\nSET @HireDate = '2023-01-01';\nSET @IsActive = 1;\n```\n\n### 2. Table Variables\n\n**Definition:** Table variables are used to store a result set in the form of a table. They are similar to temporary tables but have some differences in scope and performance characteristics.\n\n**Example:**\n\n```sql\nDECLARE @EmployeeTable TABLE (\n    EmployeeID INT,\n    EmployeeName NVARCHAR(50),\n    HireDate DATETIME\n);\n\nINSERT INTO @EmployeeTable (EmployeeID, EmployeeName, HireDate)\nVALUES (1, 'John Doe', '2023-01-01');\n\nSELECT * FROM @EmployeeTable;\n```\n\n### 3. System Variables\n\n**Definition:** System variables, also known as system functions, provide information about the SQL Server environment and the state of the current session.\n\n**Common System Variables:**\n\n- **@@ROWCOUNT:** Returns the number of rows affected by the last statement.\n- **@@IDENTITY:** Returns the last-inserted identity value.\n- **@@ERROR:** Returns the error number for the last Transact-SQL statement executed.\n- **@@TRANCOUNT:** Returns the number of active transactions.\n\n**Example:**\n\n```sql\n-- Example using @@ROWCOUNT\nUPDATE Employees\nSET IsActive = 1\nWHERE HireDate \u003c '2023-01-01';\n\nSELECT @@ROWCOUNT AS RowsAffected;\n\n-- Example using @@IDENTITY\nINSERT INTO Employees (EmployeeName, HireDate, IsActive)\nVALUES ('Jane Smith', '2024-01-01', 1);\n\nSELECT @@IDENTITY AS LastInsertedID;\n```\n\n### 4. Global Variables\n\n**Definition:** Global variables, also known as global functions, provide information about the global state of the SQL Server instance. These are prefixed with `@@` and are predefined by SQL Server.\n\n**Common Global Variables:**\n\n- **@@VERSION:** Returns the version of SQL Server.\n- **@@SERVERNAME:** Returns the name of the local server.\n- **@@MAX_CONNECTIONS:** Returns the maximum number of simultaneous user connections allowed.\n- **@@LANGUAGE:** Returns the language currently in use.\n\n**Example:**\n\n```sql\nSELECT @@VERSION AS SQLServerVersion;\nSELECT @@SERVERNAME AS ServerName;\nSELECT @@MAX_CONNECTIONS AS MaxConnections;\nSELECT @@LANGUAGE AS CurrentLanguage;\n```\n\n### 5. Cursor Variables\n\n**Definition:** Cursor variables are used to handle cursors, which are database objects used to retrieve data row-by-row from a result set.\n\n**Example:**\n\n```sql\nDECLARE @EmployeeCursor CURSOR;\nDECLARE @EmployeeID INT, @EmployeeName NVARCHAR(50);\n\nSET @EmployeeCursor = CURSOR FOR\nSELECT EmployeeID, EmployeeName\nFROM Employees;\n\nOPEN @EmployeeCursor;\nFETCH NEXT FROM @EmployeeCursor INTO @EmployeeID, @EmployeeName;\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n    PRINT 'Employee ID: ' + CAST(@EmployeeID AS NVARCHAR(10)) + ', Employee Name: ' + @EmployeeName;\n    FETCH NEXT FROM @EmployeeCursor INTO @EmployeeID, @EmployeeName;\nEND;\n\nCLOSE @EmployeeCursor;\nDEALLOCATE @EmployeeCursor;\n```\n\n### Summary\n\n- **Scalar Variables:** Store single values of specific data types.\n- **Table Variables:** Store result sets in table format.\n- **System Variables:** Provide information about the SQL Server environment and session state.\n- **Global Variables:** Provide global information about the SQL Server instance.\n- **Cursor Variables:** Manage cursors for row-by-row data retrieval.\n\nThese different types of variables allow for flexible and powerful data handling and manipulation in T-SQL.\n\n## **Declare a Variable in T-SQL**\n\nIn Transact-SQL (T-SQL), variables are declared using the `DECLARE` statement. Variables are used to store temporary data for manipulation and can be of different data types. Here is how you declare and use a variable in T-SQL:\n\n### Syntax\n\n```sql\nDECLARE @variable_name datatype;\n```\n\n### Examples\n\n1. **Declaring a Single Variable:**\n\n   ```sql\n   DECLARE @MyVariable INT;\n   ```\n\n2. **Declaring Multiple Variables:**\n\n   ```sql\n   DECLARE @MyVariable1 INT, @MyVariable2 NVARCHAR(50), @MyVariable3 DATETIME;\n   ```\n\n3. **Setting a Value to a Variable:**\n\n   ```sql\n   DECLARE @MyVariable INT;\n   SET @MyVariable = 10;\n   ```\n\n4. **Using SELECT to Set a Value:**\n\n   ```sql\n   DECLARE @MyVariable INT;\n   SELECT @MyVariable = 10;\n   ```\n\n5. **Using Variables in a Query:**\n\n   ```sql\n   DECLARE @EmployeeID INT;\n   SET @EmployeeID = 1;\n   \n   SELECT FirstName, LastName\n   FROM Employees\n   WHERE ID = @EmployeeID;\n   ```\n\n### Detailed Example:\n\n```sql\n-- Declare variables\nDECLARE @FirstName NVARCHAR(50), @LastName NVARCHAR(50), @EmployeeID INT;\n\n-- Set values to variables\nSET @FirstName = 'John';\nSET @LastName = 'Doe';\nSET @EmployeeID = 123;\n\n-- Use variables in a query\nSELECT @FirstName AS FirstName, @LastName AS LastName, @EmployeeID AS EmployeeID;\n\n-- Another example with data retrieval\nDECLARE @DepartmentID INT;\nSET @DepartmentID = 2;\n\nSELECT EmployeeID, EmployeeName\nFROM Employees\nWHERE DepartmentID = @DepartmentID;\n```\n\n### Points to Remember:\n\n- **Naming Conventions:** Variable names in T-SQL start with an `@` symbol.\n- **Data Types:** The variable's data type must be specified at the time of declaration.\n- **Scope:** The scope of a variable is limited to the batch, stored procedure, or function in which it is declared.\n\nUsing variables can help make your T-SQL scripts more flexible and easier to manage, especially when dealing with dynamic queries or performing iterative operations.\n\n- **SQL syntax and structure**\n  - **Basic SQL Statement Structure:**\n    - Keywords: SELECT, INSERT, UPDATE, DELETE, FROM, WHERE, JOIN.\n    - Statement terminator: `;` (optional but recommended).\n    - Comments: `--` for single line, `/* ... */` for multi-line.\n  - **Basic Query Structure:**\n\n    ```sql\n    SELECT column1, column2\n    FROM table_name\n    WHERE condition\n    ORDER BY column1;\n    ```\n\n- **Data types in SQL Server**\n  - **Numeric Data Types:**\n    - `INT`, `FLOAT`, `DECIMAL`, `NUMERIC`, `MONEY`\n  - **String Data Types:**\n    - `CHAR`, `VARCHAR`, `TEXT`, `NCHAR`, `NVARCHAR`, `NTEXT`\n  - **Date and Time Data Types:**\n    - `DATE`, `TIME`, `DATETIME`, `DATETIME2`, `SMALLDATETIME`, `TIMESTAMP`\n  - **Other Data Types:**\n    - `BIT`, `BINARY`, `VARBINARY`, `UNIQUEIDENTIFIER`\n\n#### 2. Basic Queries\n\n- **SELECT statements**\n\n    ```sql\n    SELECT column1, column2\n    FROM table_name;\n    ```\n\n- **Filtering data with WHERE clause**\n\n    ```sql\n    SELECT column1, column2\n    FROM table_name\n    WHERE condition;\n    ```\n\n- **Sorting data with ORDER BY**\n\n    ```sql\n    SELECT column1, column2\n    FROM table_name\n    ORDER BY column1 [ASC|DESC];\n    ```\n\n#### 3. Joins and Subqueries\n\n**Objective:** Understand how to combine data from multiple tables and use subqueries to filter and aggregate data.\n\n- **Inner join, left join, right join, full join**\n  - **Inner Join:**\n\n    ```sql\n    SELECT a.column1, b.column2\n    FROM table1 a\n    INNER JOIN table2 b ON a.id = b.id;\n    ```\n\n  - **Left Join:**\n\n    ```sql\n    SELECT a.column1, b.column2\n    FROM table1 a\n    LEFT JOIN table2 b ON a.id = b.id;\n    ```\n\n  - **Right Join:**\n\n    ```sql\n    SELECT a.column1, b.column2\n    FROM table1 a\n    RIGHT JOIN table2 b ON a.id = b.id;\n    ```\n\n  - **Full Join:**\n\n    ```sql\n    SELECT a.column1, b.column2\n    FROM table1 a\n    FULL JOIN table2 b ON a.id = b.id;\n    ```\n\n- **Cross join**\n\n    ```sql\n    SELECT a.column1, b.column2\n    FROM table1 a\n    CROSS JOIN table2 b;\n    ```\n\n- **Subqueries and correlated subqueries**\n\n    - **Subqueries Goal** : **Goal:** A query nested inside another query to provide results that will be used by the outer query. Subqueries can return single values, lists, or entire result sets. (Example Use: Fetch data to be used in a WHERE clause or SELECT list. )\n\n    - **Correlated Subqueries Goal** : **Goal:** A subquery that references columns from the outer query, allowing it to be evaluated once for each row processed by the outer query. (**Example Use:** Perform row-by-row calculations or comparisons, such as finding rows where a certain condition holds true in a related table. )\n\n  - **Subquery Example:**\n\n    ```sql\n    SELECT column1\n    FROM table1\n    WHERE column2 = (SELECT column2 FROM table2 WHERE condition);\n    ```\n\n  - **Correlated Subquery Example:**\n\n    ```sql\n    SELECT a.column1\n    FROM table1 a\n    WHERE a.column2 = (SELECT MAX(b.column2) FROM table2 b WHERE b.column1 = a.column1);\n    ```\n\n#### 4. Basic Data Manipulation\n\n- **INSERT statements**\n\n    ```sql\n    INSERT INTO table_name (column1, column2)\n    VALUES (value1, value2);\n    ```\n\n- **UPDATE statements**\n\n    ```sql\n    UPDATE table_name\n    SET column1 = value1, column2 = value2\n    WHERE condition;\n    ```\n\n- **DELETE statements**\n\n    ```sql\n    DELETE FROM table_name\n    WHERE condition;\n    ```\n\n---\n\n### Module 3: Advanced SQL Queries\n\n#### 1. Advanced SELECT Statements\n\n- **GROUP BY and HAVING clauses**\n\n    ```sql\n    SELECT column1, COUNT(*)\n    FROM table_name\n    GROUP BY column1\n    HAVING COUNT(*) \u003e 1;\n    ```\n\n- **Using aggregate functions (SUM, AVG, COUNT, etc.)**\n\n    ```sql\n    SELECT SUM(column) FROM table_name;\n    SELECT AVG(column) FROM table_name;\n    SELECT COUNT(column) FROM table_name;\n    SELECT MAX(column) FROM table_name;\n    SELECT MIN(column) FROM table_name;\n    ```\n\n#### 2. Advanced Joins and Set Operations\n\n- **Self-joins**\n\n    ```sql\n    SELECT a.column1, b.column2\n    FROM table_name a, table_name b\n    WHERE a.id = b.id;\n    ```\n\n- **UNION, INTERSECT, EXCEPT**\n  - **UNION:**\n\n    **Goal:** Combine the results of two or more SELECT queries into a single result set, eliminating duplicate rows. ( Example Use: Retrieve all rows from multiple tables with the same structure).\n\n    ```sql\n    SELECT column1 FROM table1\n    UNION\n    SELECT column1 FROM table2;\n    ```\n\n  - **INTERSECT:**\n\n    **Goal:** Return only the rows that are common to the results of two SELECT queries. (Example Use: Find common entries between two tables or result sets).\n\n    ```sql\n    SELECT column1 FROM table1\n    INTERSECT\n    SELECT column1 FROM table2;\n    ```\n\n  - **EXCEPT:**\n\n    **Goal:** Return the rows from the first SELECT query that are not present in the second SELECT query. (Example Use: Identify records in one table that do not exist in another.)\n\n    ```sql\n    SELECT column1 FROM table1\n    EXCEPT\n    SELECT column1 FROM table2;\n    ```\n\n#### 3. Common Table Expressions (CTEs)\n\n**Goal:** Simplify complex queries by breaking them into simpler subqueries that can be referenced within the main query. CTEs can also be recursive, allowing for operations on hierarchical data.\n\n- **Introduction to CTEs**\n\n    ```sql\n    WITH CTE AS (\n        SELECT column1, column2\n        FROM table_name\n        WHERE condition\n    )\n    SELECT * FROM CTE;\n    ```\n\n- **Recursive CTEs**\n\n    ```sql\n    WITH CTE AS (\n        SELECT column1, column2\n        FROM table_name\n        WHERE condition\n        UNION ALL\n        SELECT column1, column2\n        FROM table_name\n        INNER JOIN CTE ON table_name.column1 = CTE.column1\n    )\n    SELECT * FROM CTE;\n    ```\n\n---\n\n### Module 4: SQL Server Programming\n\n#### 1. Stored Procedures\n\n**Definition:** A stored procedure is a precompiled collection of one or more SQL statements stored under a name and processed as a unit. They can be invoked by name and can accept input parameters, return output parameters, and produce a result set.\n\n**Goal:** To encapsulate frequently used or complex queries and operations, improve performance through precompilation, and enhance security by controlling access to data.\n\n- **Creating and Executing Stored Procedures**\n  - **Syntax:**\n\n    ```sql\n    CREATE PROCEDURE procedure_name\n    AS\n    BEGIN\n        SQL statements\n    END;\n    ```\n\n  - **Example:**\n\n    ```sql\n    CREATE PROCEDURE GetEmployeeDetails\n    AS\n    BEGIN\n        SELECT * FROM Employees;\n    END;\n    ```\n\n  - **Executing:**\n\n    ```sql\n    EXEC GetEmployeeDetails;\n    ```\n\n- **Input and Output Parameters**\n  - **Syntax:**\n\n    ```sql\n    CREATE PROCEDURE procedure_name\n    @input_param INT,\n    @output_param INT OUTPUT\n    AS\n    BEGIN\n        SQL statements\n    END;\n    ```\n\n  - **Example:**\n\n    ```sql\n    CREATE PROCEDURE GetEmployeeByID\n    @EmployeeID INT,\n    @EmployeeName NVARCHAR(50) OUTPUT\n    AS\n    BEGIN\n        SELECT @EmployeeName = Name\n        FROM Employees\n        WHERE ID = @EmployeeID;\n    END;\n    ```\n\n  - **Executing with Parameters:**\n\n    ```sql\n    DECLARE @Name NVARCHAR(50);\n    EXEC GetEmployeeByID @EmployeeID = 1, @EmployeeName = @Name OUTPUT;\n    SELECT @Name;\n    ```\n\n#### 2. User-Defined Functions (UDFs)\n\n**Definition:** UDFs are functions created by the user to encapsulate reusable code for calculations or data transformations. They can be scalar (returning a single value) or table-valued (returning a table).\n\n**Goal:** To modularize code for reuse, maintainability, and to simplify complex calculations and operations in queries.\n\n- **Scalar Functions**\n  - **Definition:** Returns a single value based on the input parameters.\n  - **Syntax:**\n\n    ```sql\n    CREATE FUNCTION function_name (@param1 INT)\n    RETURNS INT\n    AS\n    BEGIN\n        RETURN @param1 * 2;\n    END;\n    ```\n\n  - **Example:**\n\n    ```sql\n    CREATE FUNCTION GetDouble (@Number INT)\n    RETURNS INT\n    AS\n    BEGIN\n        RETURN @Number * 2;\n    END;\n    ```\n\n  - **Usage:**\n\n    ```sql\n    SELECT dbo.GetDouble(5);\n    ```\n\n- **Table-Valued Functions**\n  - **Definition:** Returns a table data type that can be used like a table in queries.\n  - **Syntax:**\n\n    ```sql\n    CREATE FUNCTION function_name (@param1 INT)\n    RETURNS TABLE\n    AS\n    RETURN\n    (\n        SELECT columns\n        FROM table_name\n        WHERE condition\n    );\n    ```\n\n  - **Example:**\n\n    ```sql\n    CREATE FUNCTION GetEmployeesByDepartment (@DepartmentID INT)\n    RETURNS TABLE\n    AS\n    RETURN\n    (\n        SELECT * FROM Employees\n        WHERE DepartmentID = @DepartmentID\n    );\n    ```\n\n  - **Usage:**\n\n    ```sql\n    SELECT * FROM dbo.GetEmployeesByDepartment(1);\n    ```\n\n#### 3. Triggers\n\n**Definition:** Triggers are special types of stored procedures that automatically execute (or \"fire\") when specific actions occur in the database, such as INSERT, UPDATE, or DELETE.\n\n**Goal:** To enforce business rules, maintain data integrity, and perform automatic actions in response to changes in the database.\n\n- **Introduction to Triggers**\n  - **Definition:** Automatically invoked in response to certain events on a table or view.\n  - **Types:** DML Triggers (Data Manipulation Language) and DDL Triggers (Data Definition Language).\n\n- **AFTER and INSTEAD OF Triggers**\n  - **AFTER Triggers:** Execute after the triggering action has been completed.\n    - **Syntax:**\n\n      ```sql\n      CREATE TRIGGER trigger_name\n      ON table_name\n      AFTER INSERT, UPDATE, DELETE\n      AS\n      BEGIN\n          SQL statements\n      END;\n      ```\n\n    - **Example:**\n\n      ```sql\n      CREATE TRIGGER trgAfterInsert\n      ON Employees\n      AFTER INSERT\n      AS\n      BEGIN\n          PRINT 'Record Inserted';\n      END;\n      ```\n\n  - **INSTEAD OF Triggers:** Execute in place of the triggering action, allowing custom actions.\n    - **Syntax:**\n\n      ```sql\n      CREATE TRIGGER trigger_name\n      ON table_name\n      INSTEAD OF INSERT, UPDATE, DELETE\n      AS\n      BEGIN\n          SQL statements\n      END;\n      ```\n\n    - **Example:**\n\n      ```sql\n      CREATE TRIGGER trgInsteadOfInsert\n      ON Employees\n      INSTEAD OF INSERT\n      AS\n      BEGIN\n          PRINT 'Insert operation intercepted';\n      END;\n      ```\n\n#### 4. Views\n\n**Definition:** A view is a virtual table based on the result-set of a SELECT query. Views do not store data physically but display data from one or more tables.\n\n**Goal:** To simplify complex queries, enhance security by restricting access to certain columns, and present data in a specific format.\n\n- **Creating and Managing Views**\n  - **Syntax:**\n\n    ```sql\n    CREATE VIEW view_name AS\n    SELECT columns\n    FROM table_name\n    WHERE condition;\n    ```\n\n  - **Example:**\n\n    ```sql\n    CREATE VIEW vwEmployees AS\n    SELECT FirstName, LastName, Department\n    FROM Employees\n    WHERE IsActive = 1;\n    ```\n\n- **Indexed Views**\n  - **Definition:** Views that have a unique clustered index, making the data physically stored and improving performance for certain types of queries.\n  - **Syntax:**\n\n    ```sql\n    CREATE VIEW view_name WITH SCHEMABINDING AS\n    SELECT columns\n    FROM table_name\n    WHERE condition;\n\n    CREATE UNIQUE CLUSTERED INDEX index_name\n    ON view_name (column);\n    ```\n\n  - **Example:**\n\n    ```sql\n    CREATE VIEW vwActiveEmployees WITH SCHEMABINDING AS\n    SELECT FirstName, LastName, Department\n    FROM dbo.Employees\n    WHERE IsActive = 1;\n\n    CREATE UNIQUE CLUSTERED INDEX idxActiveEmployees\n    ON vwActiveEmployees (FirstName, LastName);\n    ```\n\n---\n\n## More informations and lessons :\n\n### stored procedure in T-SQL\n\n- **CREATE PROCEDURE** Statement: This is used to define and create the stored procedure. It specifies the procedure name, input parameters (if any), and the code block containing the procedure's logic.\n\n- **Input Parameters**: These are optional parameters that are passed to the procedure for execution. They are specified within parentheses after the procedure name.\n\n- **AS** Statement: This part of the procedure declaration indicates the beginning of the code block where the procedure's logic is defined.\n\n- **BEGIN...END** Block: This block contains the main logic of the procedure. It consists of SQL statements, control-of-flow statements (like IF...ELSE, WHILE, etc.), variable declarations if needed, and calls to other stored procedures or functions.\n\n- Variable Declarations: These are optional statements where you declare local variables that are used within the procedure for computation.\n\n- Output Parameters: These are optional parameters that can be used to return values from the procedure back to the calling code.\n\n- RETURN Statement: This statement is used to explicitly return from the procedure before its end.\n\n- Error Handling: Error handling code can be included to handle exceptions or errors that occur during the execution of the procedure.\n\nHere's a basic structure of a stored procedure in T-SQL:\n\n``` sql\nCREATE PROCEDURE [schema_name.]procedure_name \n    @parameter1 data_type1,\n    @parameter2 data_type2,\n    ...\nAS\nBEGIN\n    -- Variable declarations\n    DECLARE @variable1 data_type1;\n    DECLARE @variable2 data_type2;\n\n    -- Main logic of the procedure\n    -- SQL statements, control-of-flow statements, etc.\n\n    -- RETURN statement (optional)\n    -- RETURN result;\n\n    -- Error handling (optional)\n    -- BEGIN TRY\n    --     ...\n    -- END TRY\n    -- BEGIN CATCH\n    --     ...\n    -- END CATCH\nEND;\n```\n\nIn this structure:\n\n- schema_name: (Optional) The schema in which the procedure will be created.\n- procedure_name: The name of the procedure.\n- @parameter1, @parameter2, ...: Input parameters to the procedure.\n- @variable1, @variable2, ...: Local variables used within the procedure.\n- result: The value or result set returned by the procedure (if any).\n- Error handling block (optional): Used to handle exceptions or errors that occur during the execution of the procedure.\n\n-----\n\n### stored function in T-SQL\n\n- CREATE FUNCTION Statement: This is used to define and create the function. It specifies the function name, input parameters, return type, and the code block containing the function's logic.\n\n- Input Parameters: These are optional parameters that are passed to the function for computation. They are specified within parentheses after the function name.\n\n- Returns Clause: This part of the function declaration specifies the data type that the function will return. In T-SQL, the RETURNS keyword is used to define the return type.\n\n- BEGIN...END Block: This block contains the main logic of the function. It consists of SQL statements, control-of-flow statements (like IF...ELSE, WHILE, etc.), and variable declarations if needed.\n\n- Variable Declarations: These are optional statements where you declare local variables that are used within the function for computation.\n\n- RETURN Statement: This statement is used to return the result of the function. It can return a single value, a table, or a result set, depending on the function's purpose.\n\nHere's a basic structure of a stored function in T-SQL:\n\n```sql\nCREATE FUNCTION [schema_name.]function_name \n    (@parameter1 data_type1, @parameter2 data_type2, ...)\nRETURNS return_data_type\nAS\nBEGIN\n    -- Variable declarations\n    DECLARE @variable1 data_type1;\n    DECLARE @variable2 data_type2;\n\n    -- Main logic of the function\n    -- SQL statements, control-of-flow statements, etc.\n\n    -- RETURN statement\n    RETURN result;\nEND;\n```\n\nIn this structure:\n\n- schema_name: (Optional) The schema in which the function will be created.\n- function_name: The name of the function.\n- @parameter1, @parameter2, ...: Input parameters to the function.\n- return_data_type: The data type that the function will return.\n- @variable1, @variable2, ...: Local variables used within the function.\n- result: The value or result set returned by the function.\n\n---\n\nStored functions and stored procedures are both database objects that contain a set of SQL statements for performing a specific task. However, there are some key differences between the two:\n\n1- Return Value:\n\n- Stored Function: A stored function must return a value. It typically computes and returns a single scalar value (such as an integer, string, or date).\n- Stored Procedure: A stored procedure does not have to return a value, although it can optionally return one or more result sets or output parameters.\n\n2- Usage:\n\n- Stored Function: Functions are typically used within SQL statements, such as in SELECT, WHERE, and ORDER BY clauses, or assigned to variables.\n- Stored Procedure: Procedures are typically called as standalone units of work from within an application or another stored procedure.\n\n3- Transaction Control:\n\n- Stored Function: Functions cannot contain statements that directly modify database state (e.g., INSERT, UPDATE, DELETE), and they cannot perform transaction control operations like COMMIT or ROLLBACK.\n- Stored Procedure: Procedures can contain statements that modify database state, and they can perform transaction control operations.\n\n4- Input/Output Parameters:\n\n- Stored Function: Functions can have input parameters but cannot have output parameters. The return value serves as the output.\n- Stored Procedure: Procedures can have both input and output parameters.\n\n5- Portability:\n\n- Stored Function: Functions are often more portable across different database systems because they are typically used within SQL statements and adhere to SQL standards.\n- Stored Procedure: Procedures may have syntax and behavior specific to the database system in which they are created, making them less portable.\n\n6- Function Overloading:\n\n- Stored Function: Some database systems support function overloading, allowing multiple functions with the same name but different parameter lists. This feature is not standard in SQL.\n- Stored Procedure: Procedures do not support overloading in most database systems.\n\nIn summary, stored functions are designed primarily for computation and return a single value, while stored procedures are more versatile and can perform a wider range of tasks, including data modification and transaction control.\n\n---\n\n### T-SQL constructs\n\nSure, here are examples for each of the T-SQL constructs mentioned:\n\n### IF...ELSE Statement\n\n**Definition:** The `IF...ELSE` statement allows for conditional execution of T-SQL code blocks.\n\n**Example:**\n\n```sql\nDECLARE @Score INT;\nSET @Score = 85;\n\nIF @Score \u003e= 90\nBEGIN\n    PRINT 'Grade: A';\nEND\nELSE IF @Score \u003e= 80\nBEGIN\n    PRINT 'Grade: B';\nEND\nELSE IF @Score \u003e= 70\nBEGIN\n    PRINT 'Grade: C';\nEND\nELSE\nBEGIN\n    PRINT 'Grade: F';\nEND;\n```\n\n### CASE Statement\n\n**Definition:** The `CASE` statement allows for conditional logic within a query.\n\n**Example:**\n\n```sql\nDECLARE @Score INT;\nSET @Score = 85;\n\nSELECT \n    CASE\n        WHEN @Score \u003e= 90 THEN 'Grade: A'\n        WHEN @Score \u003e= 80 THEN 'Grade: B'\n        WHEN @Score \u003e= 70 THEN 'Grade: C'\n        ELSE 'Grade: F'\n    END AS Grade;\n```\n\n### WHILE Loop\n\n**Definition:** The `WHILE` loop repeatedly executes a block of code as long as the specified condition is true.\n\n**Example:**\n\n```sql\nDECLARE @Counter INT;\nSET @Counter = 1;\n\nWHILE @Counter \u003c= 5\nBEGIN\n    PRINT 'Counter Value: ' + CAST(@Counter AS NVARCHAR(10));\n    SET @Counter = @Counter + 1;\nEND;\n```\n\n### GOTO Statement\n\n**Definition:** The `GOTO` statement transfers control to a specified label within the T-SQL code.\n\n**Example:**\n\n```sql\nDECLARE @Counter INT;\nSET @Counter = 1;\n\nPRINT 'Start of the script';\n\nStartLoop:\nIF @Counter \u003c= 5\nBEGIN\n    PRINT 'Counter Value: ' + CAST(@Counter AS NVARCHAR(10));\n    SET @Counter = @Counter + 1;\n    GOTO StartLoop;\nEND;\n\nPRINT 'End of the script';\n```\n\n### WAITFOR Statement\n\n**Definition:** The `WAITFOR` statement delays the execution of the next statement until a specified time or for a specified duration.\n\n**Example:**\n\n```sql\nPRINT 'Wait for 9:12 AM';\nWAITFOR TIME '09:12';\nPRINT 'This message is printed at 9:12 AM';\n\n-- Alternatively, waiting for a duration (e.g., 10 seconds)\nPRINT 'Wait for 10 seconds';\nWAITFOR DELAY '00:00:10';\nPRINT 'This message is printed after a 10-second delay';\n```\n\n### Summary\n\n- **IF...ELSE:** Conditional execution based on specified conditions.\n- **CASE:** Conditional logic within a query.\n- **WHILE:** Looping construct to execute code repeatedly while a condition is true.\n- **GOTO:** Transfers control to a labeled section of code.\n- **WAITFOR:** Delays the execution of the next statement until a specified time or for a specified duration.\n\nThese examples demonstrate the use of conditional, looping, and control flow constructs in T-SQL, providing powerful tools for managing and manipulating data in SQL Server.\n\n----\n\n### Transaction in T-SQL\n\n**Definition:**\nA transaction in T-SQL is a sequence of operations performed as a single logical unit of work. A transaction ensures that either all operations within the transaction are completed successfully, or none of them are, maintaining the integrity of the database. Transactions follow the ACID properties: Atomicity, Consistency, Isolation, and Durability.\n\n### Syntax:\n\n#### Basic Syntax\n\n```sql\nBEGIN TRANSACTION;\n-- SQL statements go here\nCOMMIT TRANSACTION; -- or ROLLBACK TRANSACTION;\n```\n\n#### Key Statements:\n\n- **BEGIN TRANSACTION:** Starts a new transaction.\n- **COMMIT TRANSACTION:** Saves all changes made during the transaction.\n- **ROLLBACK TRANSACTION:** Undoes all changes made during the transaction.\n\n### Examples:\n\n#### Example 1: Simple Transaction\n\n```sql\nBEGIN TRANSACTION;\n\n-- Insert a new employee\nINSERT INTO Employees (FirstName, LastName, HireDate)\nVALUES ('John', 'Doe', '2023-01-01');\n\n-- Update another employee's information\nUPDATE Employees\nSET LastName = 'Smith'\nWHERE EmployeeID = 1;\n\n-- Check for errors and commit or rollback\nIF @@ERROR = 0\nBEGIN\n    COMMIT TRANSACTION;\n    PRINT 'Transaction committed successfully.';\nEND\nELSE\nBEGIN\n    ROLLBACK TRANSACTION;\n    PRINT 'Transaction rolled back due to an error.';\nEND;\n```\n\n#### Example 2: Transaction with Error Handling\n\n```sql\nBEGIN TRANSACTION;\n\nBEGIN TRY\n    -- Insert a new department\n    INSERT INTO Departments (DepartmentName)\n    VALUES ('Sales');\n\n    -- Insert a new employee in the new department\n    INSERT INTO Employees (FirstName, LastName, DepartmentID)\n    VALUES ('Jane', 'Doe', SCOPE_IDENTITY());\n\n    -- Commit transaction\n    COMMIT TRANSACTION;\n    PRINT 'Transaction committed successfully.';\nEND TRY\nBEGIN CATCH\n    -- Rollback transaction in case of error\n    ROLLBACK TRANSACTION;\n    PRINT 'Transaction rolled back due to an error.';\n    PRINT ERROR_MESSAGE();\nEND CATCH;\n```\n\n#### Example 3: Nested Transactions\n\n```sql\nBEGIN TRANSACTION OuterTransaction;\n\n-- Insert a new product\nINSERT INTO Products (ProductName, Price)\nVALUES ('New Product', 100);\n\nBEGIN TRANSACTION InnerTransaction;\n-- Update an existing product's price\nUPDATE Products\nSET Price = 120\nWHERE ProductID = 1;\n\n-- Commit or rollback inner transaction based on condition\nIF @@ERROR = 0\nBEGIN\n    COMMIT TRANSACTION InnerTransaction;\n    PRINT 'Inner transaction committed.';\nEND\nELSE\nBEGIN\n    ROLLBACK TRANSACTION InnerTransaction;\n    PRINT 'Inner transaction rolled back.';\nEND;\n\n-- Commit or rollback outer transaction based on condition\nIF @@ERROR = 0\nBEGIN\n    COMMIT TRANSACTION OuterTransaction;\n    PRINT 'Outer transaction committed.';\nEND\nELSE\nBEGIN\n    ROLLBACK TRANSACTION OuterTransaction;\n    PRINT 'Outer transaction rolled back.';\nEND;\n```\n\n### Points to Remember:\n\n1. **Atomicity:** Ensures all operations within the transaction are completed successfully or none are.\n2. **Consistency:** Ensures the database remains in a consistent state before and after the transaction.\n3. **Isolation:** Ensures that transactions are isolated from each other until they are completed.\n4. **Durability:** Ensures that once a transaction is committed, it remains so, even in the event of a system failure.\n\nBy using transactions, you can maintain the integrity and consistency of your database, especially in complex and multi-step operations.\n\n---\n\n### Constraints in T-SQL\n\nIn T-SQL, constraints are rules applied to columns or tables to enforce data integrity and define the conditions that data must meet. They ensure the accuracy and reliability of data within the database. Here are the various types of constraints available in T-SQL:\n\n### 1. Primary Key Constraint\n\n**Definition:** Ensures that each row in a table has a unique and non-null value for the specified column or columns. A table can have only one primary key.\n\n**Syntax:**\n\n```sql\nCREATE TABLE Employees (\n    EmployeeID INT PRIMARY KEY,\n    FirstName NVARCHAR(50),\n    LastName NVARCHAR(50)\n);\n```\n\n**Example:**\n\n```sql\nALTER TABLE Employees\nADD CONSTRAINT PK_EmployeeID PRIMARY KEY (EmployeeID);\n```\n\n### 2. Foreign Key Constraint\n\n**Definition:** Ensures that the value in one column (or a group of columns) matches a value in the primary key column of another table, enforcing referential integrity.\n\n**Syntax:**\n\n```sql\nCREATE TABLE Orders (\n    OrderID INT PRIMARY KEY,\n    EmployeeID INT,\n    OrderDate DATE,\n    CONSTRAINT FK_Employee FOREIGN KEY (EmployeeID)\n    REFERENCES Employees(EmployeeID)\n);\n```\n\n**Example:**\n\n```sql\nALTER TABLE Orders\nADD CONSTRAINT FK_EmployeeID FOREIGN KEY (EmployeeID)\nREFERENCES Employees(EmployeeID);\n```\n\n### 3. Unique Constraint\n\n**Definition:** Ensures that all values in a column or a group of columns are unique across the table.\n\n**Syntax:**\n\n```sql\nCREATE TABLE Customers (\n    CustomerID INT PRIMARY KEY,\n    Email NVARCHAR(100) UNIQUE\n);\n```\n\n**Example:**\n\n```sql\nALTER TABLE Customers\nADD CONSTRAINT UQ_Email UNIQUE (Email);\n```\n\n### 4. Check Constraint\n\n**Definition:** Ensures that the value in a column meets a specified condition.\n\n**Syntax:**\n\n```sql\nCREATE TABLE Products (\n    ProductID INT PRIMARY KEY,\n    ProductName NVARCHAR(100),\n    Price DECIMAL(10, 2),\n    CONSTRAINT CHK_Price CHECK (Price \u003e 0)\n);\n```\n\n**Example:**\n\n```sql\nALTER TABLE Products\nADD CONSTRAINT CHK_Price CHECK (Price \u003e 0);\n```\n\n### 5. Default Constraint\n\n**Definition:** Provides a default value for a column when no value is specified during an insert operation.\n\n**Syntax:**\n\n```sql\nCREATE TABLE Orders (\n    OrderID INT PRIMARY KEY,\n    OrderDate DATE DEFAULT GETDATE()\n);\n```\n\n**Example:**\n\n```sql\nALTER TABLE Orders\nADD CONSTRAINT DF_OrderDate DEFAULT GETDATE() FOR OrderDate;\n```\n\n### 6. Not Null Constraint\n\n**Definition:** Ensures that a column cannot have a NULL value.\n\n**Syntax:**\n\n```sql\nCREATE TABLE Employees (\n    EmployeeID INT PRIMARY KEY,\n    FirstName NVARCHAR(50) NOT NULL,\n    LastName NVARCHAR(50) NOT NULL\n);\n```\n\n**Example:**\n\n```sql\nALTER TABLE Employees\nALTER COLUMN FirstName NVARCHAR(50) NOT NULL;\n```\n\n### Summary of Constraints:\n\n- **Primary Key Constraint:** Ensures unique identification for rows.\n- **Foreign Key Constraint:** Enforces referential integrity between tables.\n- **Unique Constraint:** Ensures all values in a column are unique.\n- **Check Constraint:** Validates data based on a condition.\n- **Default Constraint:** Assigns a default value to a column.\n- **Not Null Constraint:** Ensures a column cannot contain NULL values.\n\nThese constraints are essential for maintaining data integrity and ensuring that the data entered into your database meets the specified rules and conditions.\n\n---\n\n### **AFTER Triggers** and **INSTEAD OF Triggers**\n\nIn SQL Server, triggers are special types of stored procedures that are automatically executed, or \"fired,\" in response to certain events on a table or view. The timing of a trigger's execution is defined by the type of trigger:\n\n### Types of Triggers\n\n1. **AFTER Triggers**\n2. **INSTEAD OF Triggers**\n\n### 1. AFTER Triggers\n\n**Definition:** An AFTER trigger fires after the SQL Server engine has performed the INSERT, UPDATE, or DELETE operation. These triggers can be used to enforce business rules, update other tables, or maintain audit trails.\n\n**Syntax:**\n\n```sql\nCREATE TRIGGER TriggerName\nON TableName\nAFTER INSERT, UPDATE, DELETE\nAS\nBEGIN\n    -- Trigger logic here\nEND;\n```\n\n### 2. INSTEAD OF Triggers\n\n**Definition:** An INSTEAD OF trigger fires instead of the triggering event. This means that the trigger is executed in place of the INSERT, UPDATE, or DELETE operation, allowing you to override the default behavior.\n\n**Syntax:**\n\n```sql\nCREATE TRIGGER TriggerName\nON TableName\nINSTEAD OF INSERT, UPDATE, DELETE\nAS\nBEGIN\n    -- Trigger logic here\nEND;\n```\n\n### Summary of Timing:\n\n- **AFTER Triggers:** Fire **after** the triggering event (INSERT, UPDATE, or DELETE) has been executed.\n- **INSTEAD OF Triggers:** Fire **instead of** the triggering event, allowing custom handling of the event.\n\n### Example Usage of AFTER and INSTEAD OF Triggers\n\n#### AFTER Trigger Example\n\n```sql\n-- Create a table to log audit information\nCREATE TABLE AuditLog (\n    AuditID INT IDENTITY(1,1) PRIMARY KEY,\n    ActionType NVARCHAR(50),\n    ActionTime DATETIME,\n    EmployeeID INT\n);\n\n-- Create an AFTER INSERT trigger to log insert actions\nCREATE TRIGGER trgAfterInsertAudit\nON Employees\nAFTER INSERT\nAS\nBEGIN\n    INSERT INTO AuditLog (ActionType, ActionTime, EmployeeID)\n    SELECT 'INSERT', GETDATE(), EmployeeID\n    FROM inserted;\nEND;\n```\n\n#### INSTEAD OF Trigger Example:\n\n```sql\n-- Create an INSTEAD OF DELETE trigger to archive deleted records\nCREATE TRIGGER trgInsteadOfDelete\nON Employees\nINSTEAD OF DELETE\nAS\nBEGIN\n    -- Insert deleted records into an archive table\n    INSERT INTO EmployeesArchive (EmployeeID, FirstName, LastName, HireDate)\n    SELECT EmployeeID, FirstName, LastName, HireDate\n    FROM deleted;\n\n    -- Perform the actual delete operation\n    DELETE FROM Employees\n    WHERE EmployeeID IN (SELECT EmployeeID FROM deleted);\nEND;\n```\n\nIn summary, **AFTER triggers** are used to execute logic after the data modification, while **INSTEAD OF triggers** override the data modification action and provide custom behavior. This flexibility allows for a wide range of use cases, from simple auditing to complex business rule enforcement.\n\n---\n\n### IDENTITY(1,1)\n\nIn SQL Server, `IDENTITY(1,1)` is used to define an identity column in a table. An identity column is a column in a table that automatically generates a unique, incrementing value for each row inserted into the table. This is particularly useful for primary keys.\n\n### Breakdown of `IDENTITY(1,1)`:\n\n- **IDENTITY:** Specifies that the column is an identity column.\n- **(1,1):** This part contains two values:\n  - The **first value** (1) is the seed, which is the starting value for the identity column.\n  - The **second value** (1) is the increment, which is the value by which the identity column is incremented for each new row.\n\n### Example\n\nHere is an example of how `IDENTITY(1,1)` is used in a table definition:\n\n```sql\nCREATE TABLE Employees (\n    EmployeeID INT IDENTITY(1,1) PRIMARY KEY,\n    FirstName NVARCHAR(50),\n    LastName NVARCHAR(50),\n    HireDate DATE\n);\n```\n\n### Explanation:\n\n- **EmployeeID INT IDENTITY(1,1):** This defines `EmployeeID` as an identity column that starts at 1 and increments by 1 for each new row.\n  - The first row inserted into the `Employees` table will have an `EmployeeID` of 1.\n  - The second row will have an `EmployeeID` of 2.\n  - The third row will have an `EmployeeID` of 3, and so on.\n\nThis automatic generation of unique values ensures that each `EmployeeID` is unique and can be used as a primary key to uniquely identify each row in the table.\n\n### Example with Data Insertion\n\n```sql\nINSERT INTO Employees (FirstName, LastName, HireDate)\nVALUES ('John', 'Doe', '2023-01-01');\n\nINSERT INTO Employees (FirstName, LastName, HireDate)\nVALUES ('Jane', 'Smith', '2023-02-01');\n\nSELECT * FROM Employees;\n```\n\n### Result:\n\n| EmployeeID | FirstName | LastName | HireDate   |\n|------------|-----------|----------|------------|\n| 1          | John      | Doe      | 2023-01-01 |\n| 2          | Jane      | Smith    | 2023-02-01 |\n\nIn this example:\n- The first row inserted has an `EmployeeID` of 1.\n- The second row inserted has an `EmployeeID` of 2.\n\nBy using `IDENTITY(1,1)`, SQL Server ensures that `EmployeeID` is automatically and uniquely assigned to each new row, starting at 1 and incrementing by 1 for each subsequent row.\n\n---\n\n### `deleted` and `inserted` tables in triggers\n\nIn the context of SQL Server triggers, the `deleted` and `inserted` tables are special, temporary tables that are automatically created by the SQL Server engine during the execution of a trigger. They are used to hold the old and new values of the data being modified by an `UPDATE`, `INSERT`, or `DELETE` statement.\n\n### Explanation:\n\n- **`deleted` Table:**\n  - Contains the old values of the rows that were either deleted or updated.\n  - Used in `DELETE` and `UPDATE` triggers to capture the state of the data before the modification.\n\n- **`inserted` Table:**\n  - Contains the new values of the rows that were either inserted or updated.\n  - Used in `INSERT` and `UPDATE` triggers to capture the state of the data after the modification.\n\n### Example Scenarios:\n\n#### DELETE Trigger Example:\n\nA `DELETE` trigger uses the `deleted` table to handle rows that are being removed from the table.\n\n```sql\n-- Create a table for archiving deleted records\nCREATE TABLE EmployeesArchive (\n    EmployeeID INT,\n    FirstName NVARCHAR(50),\n    LastName NVARCHAR(50),\n    HireDate DATE\n);\n\n-- Create a trigger to archive deleted records\nCREATE TRIGGER trgAfterDelete\nON Employees\nAFTER DELETE\nAS\nBEGIN\n    -- Insert deleted records into the archive table\n    INSERT INTO EmployeesArchive (EmployeeID, FirstName, LastName, HireDate)\n    SELECT EmployeeID, FirstName, LastName, HireDate\n    FROM deleted;\nEND;\n```\n\n**Explanation:**\n\n- When a `DELETE` statement is executed on the `Employees` table, the `trgAfterDelete` trigger fires.\n- The `deleted` table contains the rows that were deleted from the `Employees` table.\n- The trigger inserts these deleted rows into the `EmployeesArchive` table.\n\n#### INSERT Trigger Example:\n\nAn `INSERT` trigger uses the `inserted` table to handle rows that are being added to the table.\n\n```sql\n-- Create a trigger to log insert operations\nCREATE TRIGGER trgAfterInsert\nON Employees\nAFTER INSERT\nAS\nBEGIN\n    -- Log the insert operation\n    INSERT INTO AuditLog (ActionType, ActionTime, EmployeeID)\n    SELECT 'INSERT', GETDATE(), EmployeeID\n    FROM inserted;\nEND;\n```\n\n**Explanation:**\n\n- When an `INSERT` statement is executed on the `Employees` table, the `trgAfterInsert` trigger fires.\n- The `inserted` table contains the rows that were inserted into the `Employees` table.\n- The trigger logs these inserted rows into the `AuditLog` table.\n\n#### UPDATE Trigger Example:\n\nAn `UPDATE` trigger can use both the `deleted` and `inserted` tables to handle rows that are being modified.\n\n```sql\n-- Create a trigger to log update operations\nCREATE TRIGGER trgAfterUpdate\nON Employees\nAFTER UPDATE\nAS\nBEGIN\n    -- Log the update operation\n    INSERT INTO AuditLog (ActionType, ActionTime, EmployeeID, OldFirstName, NewFirstName)\n    SELECT 'UPDATE', GETDATE(), d.EmployeeID, d.FirstName, i.FirstName\n    FROM deleted d\n    JOIN inserted i ON d.EmployeeID = i.EmployeeID;\nEND;\n```\n\n**Explanation:**\n\n- When an `UPDATE` statement is executed on the `Employees` table, the `trgAfterUpdate` trigger fires.\n- The `deleted` table contains the rows with the old values before the update.\n- The `inserted` table contains the rows with the new values after the update.\n- The trigger logs the changes into the `AuditLog` table, including the old and new values.\n\n### Summary:\n\n- **`deleted` table:** Temporarily holds the old values of the rows affected by `DELETE` and `UPDATE` statements.\n- **`inserted` table:** Temporarily holds the new values of the rows affected by `INSERT` and `UPDATE` statements.\n\nThese special tables are integral to the functionality of triggers, allowing them to access and manipulate the data before and after the modification.\n\n---\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdrisskhattabi6%2Fsql-server-and-t-sql-lab","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdrisskhattabi6%2Fsql-server-and-t-sql-lab","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdrisskhattabi6%2Fsql-server-and-t-sql-lab/lists"}