Lecture1_DBP2024
Lecture1_DBP2024
Variables have local scope and are only visible within the batch or
procedure where they are defined.
To assign a variable a value by using the set statement, A variable can also
have a value assigned by the select statement
DECLARE @EmpIDVariable INT;
set @EmpIDVariable = 122
SELECT @EmpIDVariable = MAX (BusinessEntityID)
FROM HumanResources.Employee;
GO
T-SQL Server
Control-of-Flow Language Elements
Flow-control statements from T-SQL are rather rudimentary
compared to similar commands in other modern programming
languages such as Visual Basic and C#.
Transact-SQL statements and programming constructs:
Comments Break
CASE Statement
Continue goto
If… Else
While
WaitFor
T-SQL Server
CASE Statement
The CASE expression has two formats:
1. The simple CASE expression compares an expression to a set of simple expressions
to determine the result. -- Simple CASE expression:
CASE input_expression
WHEN when_expression THEN result_expression [ ...n ]
[ ELSE else_result_expression ]
END
-- example
IF DATENAME(weekday, GETDATE()) IN (N'Saturday', N'Sunday')
SELECT 'Weekend';
ELSE
SELECT 'Weekday';
T-SQL Server
WHILE (Transact-SQL)
-- Syntax for SQL Server
WHILE Boolean_expression
{ sql_statement | statement_block | BREAK | CONTINUE }
-- Example :
WHILE ( SELECT AVG(ListPrice) FROM dbo.DimProduct) < $300
BEGIN
UPDATE dbo.DimProduct SET ListPrice = ListPrice * 2;
SELECT MAX ( ListPrice) FROM dbo.DimProduct
IF ( SELECT MAX (ListPrice) FROM dbo.DimProduct) > $500
BREAK;
END
T-SQL Server
WAITFOR (Transact-SQL)
Blocks the execution of a batch, stored procedure, or transaction until
either a specified time or time interval elapses, or a specified statement
modifies or returns at least one row.
-- Syntax -- example waitfor
WAITFOR BEGIN
{ WAITFOR DELAY '02:00';
DELAY 'time_to_pass' EXECUTE sp_helpdb;
| TIME 'time_to_execute' END; GO
| [ ( receive_statement ) |
(get_conversation_group_statement ) ]
[ , TIMEOUT timeout ]
}
T-SQL Server
Operators (Transact-SQL)
An operator is a symbol specifying an action that is performed on one or more
expressions. The following table lists the operator categories that SQL Server uses.
1. Arithmetic operators
7. Comparison operators
2. Relational operators
8. String Concatenation
3. Assignment operator operator
4. Scope resolution operator 9. Compound operators
5. Bitwise operators 10. Unary operators
6. Set operators (EXCEPT and INTERSECT, UNION) 11. Logical operators