Lab 6
Lab 6
Tags
Table Constraints
Purpose: Enforce rules on columns to maintain data integrity and accuracy.
Types of Constraints:
PRIMARY KEY: Uniqueness + NOT NULL
Lab 6 1
Foreign Key Constraint
Links two tables together.
Example:
Unique Constraint
Ensures all values are different in a column.
Allows NULL values. (but only one null because it is unique ^^)
Check Constraint
Defines a condition that must be met.
Lab 6 2
UnitPrice int CHECK(UnitPrice > 0)
);
Default Constraint
Assigns a default value when none is provided.
Modifying Constraints
Add a new constraint to an existing table.
Lab 6 3
Drop an existing constraint from a table.
Lab 6 4
Pass parameters and use output variables for results.
Syntax:
DECLARE @identifier datatype [= expression];
Example:
Using SELECT:
Good for query results or multiple assignments.
here we are selecting values to the variables from the result of the query
Example:
Lab 6 5
Commenting Code in T-SQL
Single line: - comment
Multi-line: /* comment */
Example:
IF Statement
Syntax:
IF condition
statement;
[ELSE IF condition
statement;]
[ELSE
statement;]
Example:
Lab 6 6
IF @Price > 50
PRINT 'Expensive';
ELSE IF @Price BETWEEN 20 AND 50
PRINT 'Moderately Priced';
ELSE
PRINT 'Cheap';
WHILE Loop
Syntax:
WHILE condition
BEGIN
statement1;
statement2;
END;
Example:
Lab 6 7
Procedures: Perform actions.
Stored Procedures
Syntax:
EXEC GetAllCustomers;
Lab 6 8
//or use EXECUTE
Lab 6 9
With Multiple Parameters:
Retrieve orders within a date range.
Drop:
Practice Exercises
Practice 1:
Lab 6 10
Write a stored procedure to retrieve all orders for a given CustomerID .
Practice 2:
Write a stored procedure to calculate the total sales amount for a given
ProductID .
END;
Lab 6 11