T-sql (1)
T-sql (1)
you understand how each command works. T-SQL is an extension of SQL that adds
procedural programming capabilities to the standard SQL language.
Example:
• This query retrieves the FirstName and LastName of employees who work in the
"Sales" department.
Example:
• This query inserts a new employee into the Employees table with specific values for
FirstName, LastName, Department, and HireDate.
Example:
UPDATE Employees
SET Department = 'Marketing'
WHERE EmployeeID = 101;
• This query updates the department of the employee with EmployeeID 101 to
'Marketing'.
Example:
• This query deletes the employee with EmployeeID 101 from the Employees table.
The CREATE TABLE statement is used to define a new table structure in the database.
Example:
• This query creates a new Departments table with three columns: DepartmentID,
DepartmentName, and ManagerID.
The ALTER TABLE statement is used to modify an existing table's structure, such as adding or
deleting columns.
Example:
A stored procedure is a group of SQL statements that can be executed as a single unit.
Example:
Example:
• This query executes the GetEmployeeInfo stored procedure and passes EmployeeID
101 as an argument.
Example:
CREATE FUNCTION GetEmployeeFullName (@EmployeeID INT)
RETURNS VARCHAR(200)
AS
BEGIN
DECLARE @FullName VARCHAR(200);
SELECT @FullName = FirstName + ' ' + LastName
FROM Employees
WHERE EmployeeID = @EmployeeID;
RETURN @FullName;
END;
Example:
• This query checks if @Salary is greater than 40,000 and prints 'High salary' or 'Low
salary' accordingly.
The WHILE loop is used to repeatedly execute a block of SQL code as long as a specified
condition is true.
Example:
Example:
BEGIN TRY
-- Attempt to divide by zero (error)
SELECT 10 / 0;
END TRY
BEGIN CATCH
PRINT 'An error occurred: ' + ERROR_MESSAGE();
END CATCH;
• This query attempts to divide by zero, which causes an error. The error is caught in
the CATCH block, and an error message is printed.
Transactions ensure that a group of SQL statements are executed as a single unit.
Example:
• BEGIN TRANSACTION;
•
• UPDATE Employees
• SET Salary = Salary + 5000
• WHERE Department = 'HR';
•
• INSERT INTO Transactions (EmployeeID, Amount)
• VALUES (101, 5000);
•
• -- Simulate an error
• -- ROLLBACK TRANSACTION; -- Uncomment this to roll back the changes
•
• COMMIT TRANSACTION;.
The JOIN command is used to combine rows from two or more tables based on a related
column between them.
Summary: