T SQL Programming
T SQL Programming
T-SQL Programming
(Phần 1)
Giảng viên: Trần Quang Duy
1-Oct-08
Content
Basic Transact-SQL Programming Constructs
Identifiers
DataType
Variables
Flow-control Statements
Batches and Scripts
Temporary Tables and Table Variables
Dynamic SQL
Exception Handling
2/31
Identifiers
Main rules:
Start with any letter: A–Z and a–z..
Up to 128 characters for normal objects, 116 for temporary
objects.
Any names that are the same as SQL Server keywords or
contain embedded spaces must be enclosed in double quotes
(“”) or square brackets ([]).
3/31
Data Types
Character Strings
char, varchar, varchar(max), text
Unicode Character Strings
nchar, nvarchar, nvarchar(max), ntext
Date and Time
datetime, smalldatetime
Intger Numbers
int, smallint, tinyint, bigint, bit
Special Data Types
sql_variant
4/31
Using variables
Variable : stores values
T-SQL variables:
Start with @
Local variables: @
Global variables: @@
DECLARE statement
Datatype: must be specified
Multiple variables: single DECLARE statement with “,”
There is no way to “undeclare” variables.
5/31
Declaring Variables
Declaring Variables
DECLARE @age INT;
DECLARE @firstName CHAR(20), @lastName CHAR(20);
6/31
Assigning Values to Variables
Using the SET statement
DECLARE @age INT;
DECLARE @firstName CHAR(20), @lastName
CHAR(20);
SET @lastName='Forta';
SET @firstName='Ben';
SET @age=21;
Using the SELECT statement
SELECT @age=21;
SET or SELECT?
7/31
Viewing Variable Contents
Input:
DECLARE @age INT;
DECLARE @firstName CHAR(20), @lastName
CHAR(20);
SET @lastName='Forta';
SET @firstName='Ben';
SET @age=21;
SELECT @lastName, @firstName, @age
Output:
Forta Ben 21
8/31
Viewing Variable Contents
Input
DECLARE @age INT;
DECLARE @firstName CHAR(20),@lastName
CHAR(20);
SET @lastName='Forta';
SET @firstName='Ben';
SET @age=21;
PRINT @lastName + ', ' + @firstName;
PRINT @age;
Output
Forta , Ben
21
9/31
Using Variables in T-SQL Statements
Using Variables:
DECLARE @cust_id nchar(5);
SET @cust_id = 'ALFKI';
-- Lay thong tin cong ty, dia chi
SELECT CompanyName, Address
FROM customers
WHERE CustomerID = @cust_id
--Lay thong tin hoa don
SELECT OrderID, OrderDate
FROM ORDERS
WHERE CustomerID = @cust_id
ORDER BY OrderDate
10/31
Comment
Single-line Comments: --
-- This is a comment
-- Select * from Customers
Multiline Comments: /*…*/
/* This is a comment.
All these lines will be ignored.
*/
11/31
Using Conditional Processing
IF statement
IF <Boolean Expression>
<SQL statement> | BEGIN <code series> END
[ELSE
<SQL statement> | BEGIN <code series> END]
12/31
Using Conditional Processing
Input
DECLARE @open BIT
IF DatePart(dw, GetDate()) = 1
SET @open = 0
ELSE
SET @open = 1
-- Output
SELECT @open AS OpenForBusiness
Output
OpenForBusiness
---------------
1
13/31
Using Conditional Processing
Input
DECLARE @dow INT
DECLARE @open BIT
SET @dow = DatePart(dw, GetDate());
IF @dow = 1 OR @dow = 7
SET @open = 0
ELSE
SET @open = 1
SELECT @open AS OpenForBusiness
Output
OpenForBusiness
---------------
1 14/31
Using Conditional Processing
Input
DECLARE @dow INT
DECLARE @open BIT, @process BIT
-- Get the day of week
SET @dow = DatePart(dw, GetDate());
-- Open for business today?
IF @dow = 1 OR @dow = 7
BEGIN
SET @open = 0
SET @process = 0
END
ELSE
BEGIN
SET @open = 1
SET @process = 1
END
15/31
Using Looping
WHILE statement
WHILE <Boolean expression>
<sql statement> |
[BEGIN
<statement block>
[BREAK]
<sql statement> | <statement block>
[CONTINUE]
END]
16/31
Using Looping
Input
DECLARE @counter INT
SET @counter=1
WHILE @counter <= 10
BEGIN
PRINT @counter
SET @counter=@counter+1
END
Output
1 2 3 4 5 6 7 8 9 10
17/31
GoTo,WaitFor Statement
GoTo label . . . label:
If @@Error <> 0 Goto ERR_1
...........
ERR_1:
Print 'Error'
WaitFor {Delay 'time' | Time 'time'}
WaitFor Delay '00:01:00'
Select * from dbo.Customers
only to it
Allows different sessions to create a temporary table with the
same name
CREATE TABLE #T1(col1 INT);
Global Temporary Tables
Prefixed with a two number symbol (##).
22/31
Dynamic SQL
Dynamic SQL
EXEC (EXECUTE)
sp_executesql
Working with dynamic SQL
It runs under a separate scope than the code that calls it.
It runs under the same security context as the current user.
Permissions to execute code if the code is within a stored
procedure
It runs under the same connection and transaction context as
the calling object
Can’t do the concatenation of function in EXEC call.
EXEC can not be used inside a User Defined Function. 23/31
Dynamic SQL
EXEC (EXECUTE)
EXEC <procedure name and arguments>
Or EXEC ({<string variable>|’<literal command string>’})
Example
EXEC ('select * from dbo.customers')
---------------------------
DECLARE @InVar varchar(200)
SET @InVar = 'DECLARE @OutVar varchar(50)
SELECT @OutVar = FirstName FROM Employees
WHERE EmployeeID = 1
SELECT ''The Value Is '' + @OutVar'
-- Now run it
EXEC (@Invar) 24/31
Dynamic SQL
sp_executesql
EXEC sp_executesql
@stmt = <statement>, -- similar to proc's body
@params = <params>, -- similar to proc's params declaration
<params assignment> -- like in a procedure call
Example
DECLARE @i AS INT;
SET @i = 10248;
DECLARE @sql AS NVARCHAR(46);
SET @sql = 'SELECT * FROM dbo.Orders WHERE OrderID =
@oid;';
EXEC sp_executesql
@stmt = @sql,
@params = N'@oid AS INT',
@oid = @i;
25/31
Exception Handling
Prior to SQL Server 2005
@@Error: return an integer ( 0- success and <> 0: error code) of the last
T-SQL statement executed.
DECLARE @Error int
INSERT INTO [Order Details]
(OrderID, ProductID, UnitPrice, Quantity, Discount)
VALUES
(999999,11,10.00,10, 0)
SELECT @Error = @@ERROR
IF @Error!=0
PRINT 'The Value of @Error is ' + CONVERT(varchar,
@Error)
ELSE
PRINT 'Successed'
26/31
Exception Handling
In SQL Server 2005
TRY/CATCH
BEGIN TRY
….
END TRY
BEGIN CATCH
…
END CATCH
27/31
Exception Handling
TRY/CATCH
BEGIN TRY
INSERT INTO [Order Details](OrderID, ProductID,
UnitPrice, Quantity, Discount)
VALUES(999999,11,10.00,10, 0)
PRINT 'INSERT succeeded.';
END TRY
BEGIN CATCH
PRINT 'INSERT failed.';
/* handle error here */
END CATCH
28/31
New Exception-Handling Functions
Function Purpose
Error_Line() Returns the line number of the procedure in which the error
has occurred
29/31
Manually Raising Errors
Raiserror
Raiserror (<message ID | message string>, <severity>,
<state> [, <argument>[,<...n>]] )[WITH option[,...n]]
Raiserror ('An error occurred!', 0, 1)
sp_addmessage
Exec sp_addmessage 50001,16,'New Error'
sp_dropmessage
Exec sp_dropmessage 50001
30/31
Reference
Books online
Inside Microsoft® SQL Server™ 2005 T-SQL
Programming, Microsoft Press, 2006
Sams Teach Yourself Microsoft SQL Server 2005
Express in 24 Hours, Alison Balter, Sams Publisher,
2006
31/31