You need to specify fields’ names and data types as well as whether certaincolumns can accept NULL as a valid value by default a field does accept NULLs.Though you can use this table imm
Trang 1You need to specify fields’ names and data types as well as whether certaincolumns can accept NULL as a valid value (by default a field does accept NULLs).
Though you can use this table immediately after running a statement in the QueryAnalyzer to create it, there is a lot of room for improvement: You can specify aFOREIGN KEY, an index, computed fields, constraints, rules, default values, andmore These features will be covered in sessions 10, 16, and 26
The table created with the preceding statement is stored permanently in yourdatabase and you can view it in the Tables collection of the Enterprise Manager
But sometimes you will need to create a table that you will soon discard You cancreate a temporary table with an almost identical query:
CREATE TABLE #MyTable ( Field1 int PRIMARY KEY, Field2 char(10) NOT NULL), Field3 datetime
)The pound sign (#) as the first character specifies that the table is temporary
Temporary tables can be either local or global, the difference being the degree ofvisibility: Local tables are accessible only to the connection in which they werecreated, while global tables are accessible to all processes in all current connec-tions The global temporary-table identifier is a double pound sign as the first twocharacters of the table name, as in ##MyTable
Both local and global temporary tables are physically created in the TempDBdatabase
Altering tables
To modify an existing table you can use the ALTER statement With the followingstatement you can add or remove fields in the table, and add, drop, or disable con-straints (To modify a table you need to have the privileges of the database owner
or administrator.)ALTER TABLE MyTable ADD Field4 VARCHAR(10) NULL
To remove a field from the table, use the following command:
ALTER TABLE MyTable DROP COLUMN Field4 Some restrictions apply when you are adding fields to a table This is the when
a table already contains data; when rules exist; or if constraints or triggers arebound to the table For the complete syntax, consult Books Online
Trang 2Deleting tables
Deleting a table is just as easy as deleting an entire database:
DROP TABLE MyTableTemporary tables have a different life span from regular tables: If a temporarytable is not explicitly dropped it will be dropped as soon as the last task referenc-ing it is completed
Getting Information about Your SQL Server
SQL Server provides you with a number of system functions that you can use toretrieve some important information about it You can type these statementsdirectly into the query window and see the results in the Messages tab, as shown
in Figure 9-3 The following is a list of the most common functions; there are manymore
SELECT ←NGUAGE displays the name of your SQL Server language
SELECT @@SERVERNAME displays the name of the SQL Server for the rent connection
cur- SELECT @@VERSION displays information about Microsoft SQL Server —version, build, edition, and so on
SELECT @@TRANCOUNT displays the number of open transactions for thecurrent connection
SELECT @@ERROR displays an error number giving you a clue about thesource of an error and the reason it occurred
I’ll discuss SELECT@@TRANCOUNT in greater detail in Session 14.
Cross-Ref
Trang 3Figure 9-3
Displaying return results of the system function.
Working with the Query Analyzer Templates and the Object Browser
SQL Server comes with a number of useful templates that will save you time in ating T-SQL programs The templates are canned T-SQL framework solutions thatyou can modify for your own use You can get to the Templates dialog either fromthe toolbar of the SQL Query Analyzer or from its Edit menu Templates are avail-able for every occasion: for creating databases, creating tables, managing indexes,moving databases from server to server, and more
cre-The Object Browser (see Figure 9-4) is another important feature provided tomake your life easier In addition to the Templates browser it also includes a fulllist of supported T-SQL functions and all supported system data types The Object
Trang 4Browser also provides a full description of the functions and their accepted meters Once you’ve decided which function to use, you can transfer its text (dec-laration and arguments) into the current pane of the Query Analyzer or a newpane To do this, select the appropriate option from the right-click menu — it suredoes reduce the amount of typing you have to do
Trang 5SQL Server 2000 contains a vast collection of system functions that youcan use in your T-SQL code to perform specific tasks and retrieve systemproperties.
Query Analyzer templates and the Object Browser provide you with an easyway to locate and use specific system functions, and reduce the amount oftyping you have to do
QUIZ YOURSELF
1 What is the SQL Query Analyzer?
2 What parameter(s) is/are not optional when you’re creating a database
with T-SQL statements?
3 Where in SQL Server are temporary tables placed upon creation?
4 Is it possible to modify a table after it has been created?
5 How do you invoke the Object Browser?
6 What are system functions?
Trang 7Session Checklist
✔Declaring and using T-SQL variables
✔Using control-of-flow statements
✔Exploring T-SQL operators
✔Working with aggregate functions
✔Running subqueries
✔Using the CASE function
This session is about programming SQL Server 2000 using its own built-in
lan-guage, Transact-SQL You will learn how to produce working programs usingT-SQL, as well as when and how to use variables, T-SQL operators, conver-sions, and aggregate functions
Declaring and Using T-SQL Variables
The concept of a variable is central to programming and T-SQL is no exception Avariable is a conceptual placeholder that can contain data and to which you, theprogrammer, can assign these data at will Until a value is assigned to the variable,
Programming with T-SQL
10
Trang 8the variable is empty For strongly typed languages like T-SQL, the assigned value
of the variable must be of the same or a compatible data type
In T-SQL, as in many programming languages, a variable must be declared prior
to use The syntax for declaring a variable is simple:
DECLARE @Counter int DECLARE @FirstName varchar(25)This declares a local variable named @Counter of type integer and a local vari-able @FirstName of type varchar, which is capable of holding up to 25 characters.You can declare several variables on the same line, as in the following example:DECLARE @FirstName varchar(25), @Counter int
All local variables are preceded by the commercial at sign (@)
This example brings up another important concept — scope of variables The
variable declared in a stored procedure or a batch job is visible within it You mayfind some literature that refers to names preceded by the double at sign (@@) as
global, but in reality these are system functions that you learned about in the
pre-vious session No true global variables exist in T-SQL, which means that you not share variables between connections
can-See Session 11 for a discussion of stored procedures.
The main function of variables is to store intermediate data, keep a counter forthe loop, or return a single value from the stored procedure You assign a value to
a variable with code such as the following:
SET @Counter = 1 SET @FirstName = ‘Alex’
If the assigned value is a result of a query, the syntax is different, as follows:SELECT @FirstName = au_fname FROM authors where au_lname =
‘Carson’
You need to understand what it means if a query returns more than one row Ifthe table contains more than one record in which the last name of the person isCarson, then the last record’s au_fname value will be assigned to the variable
@FirstName For example, the following query, executed in the context of the Pubs
Cross-Ref
Trang 9database, returns two records in ascending alphabetical order (the default): first
‘Albert’ and then ‘Anne’
SELECT au_fname FROM authors WHERE au_lname = ‘Ringer’
The querySELECT @FirstName = au_fname FROM authors where au_lname =
‘Ringer’
will put ‘Anne’ into the variable @FirstName
T-SQL provides support for many different data types It is important to use thecorrect data type in order to prevent errors When dealing with financial data youmay want to use the highest-precision numeric data type to avoid rounding errors,while for an inventory count you may want to use integers to speed up processingand consume fewer system resources
Variables can be converted to different data types either explicitly or implicitly;
no data type can be converted to every other data type, but every data type can be converted to some other data type.
DECLARE @AccountValue money DECLARE @IntermediateHolder int SET @AccountValue = 1234.56
SET @IntermediateHolder = @AccountValue
At this point SQL Server implicitly converts @AccountValue into an integer and
@IntermediateHolder hereafter contains 1,234 dollars — your 56 cents are goneforever if you use @IntermediateHolder for future calculations
Trang 10Explicit conversion
In order to convert from one type to another you need to use the special sion functions CAST and CONVERT These functions behave similarly, but CAST ispreferable to CONVERT: It complies with SQL-92 standards, so you can use it whenporting your SQL code to other vendors’ products
conver-CAST ( expression AS data_type ) CONVERT ( data_type [ ( length ) ] , expression [ , style ] )Here are some examples of explicit conversion If for some reason you want toconvert all postal codes from the Authors table into numbers, you use the follow-ing statement:
SELECT CAST (zip AS int) FROM authors
It might not be obvious why you would want to turn data represented as a acter string into numbers Consider the following: The ZIP field is of the varchartype and you cannot do arithmetic with characters, but you need to add up all theZIP codes from the Authors table — your boss requires it for his astrologicalresearch You can do this using CAST and the aggregate function SUM (coveredlater in this session) The result, by the way, is 1,904,317
char-The following query using CONVERT will produce exactly the same result You donot have to specify the length of the data for the basic type, as it is implied bydefault
SELECT SUM(CONVERT ( int , ZIP)) FROM authors
When converting date/time into strings you may want to add a third
argument — style — to produce results of a specific format (such as dd/mm/yyyy).
For the full syntax of this argument see Books Online
Some data types cannot be converted into each other Figure 10-1, taken fromMicrosoft SQL Server Books Online, specifies which data types can be converted towhich others — implicitly or explicitly
Trang 11Figure 10-1
Data-type conversion options.
Using Control-of-Flow Statements
Control-of-flow statements direct the execution path based on some condition
A BEGIN END statement defines a block that executes as one; it is usually lowed by a WHILE, IF, or IF ELSE statement
fol-The classic example is the IF ELSE construct Somewhere in your HR ment database there might a T-SQL that runs once a year to update your salary inthe Salaries table, using as its criterion your Social Security number:
depart-DECLARE @increase money DECLARE @salary money
Trang 12SET @increase = $1000 SELECT @salary = salary FROM salaries WHERE ssn=’123456789’
IF @salary < $100000 BEGIN
SET @salary = @salary + @increase UPDATE salaries SET salary = @salary WHERE ssn =
‘123456789’
END ELSE PRINT ‘HAVE A NICE DAY’
Often you need to organize a loop construct to scroll through a range of ble values T-SQL provides the WHILE construct for this purpose Suppose thatmanagement decides to give everybody a bonus — within its means, of course;management does not want the total of all employees’ salaries to exceed a coolmillion dollars So it will do incremental salary increases until the preset limit
In the preceding code I used an aggregate function, SUM, that I will come back
to later in this session The loop will incrementally increase bonuses by two cent of the annual salary for all employees until the limit is reached The checkcondition of the WHILE loop must evaluate to Boolean — true or false
per-The loops can be nested: While updating bonuses you can also increase thenumber of vacation days, again based on some upper or lower limit
To give you more control over the execution of a loop T-SQL provides two
addi-tional keywords to go with the WHILE statement: BREAK and CONTINUE.
BREAK triggers an immediate exit from the innermost WHILE loop and jumps tothe line after END statement If you are using nested loops you will need to usethe BREAK statement for every loop in order to get out completely
CONTINUE immediately returns you to the WHILE condition; not a single ment following CONTINUE will be executed
state-RETURN is used in stored procedures (covered in the next session) It causesexecution to stop immediately and returns results to the calling procedure or theclient
Trang 13WAITFOR introduces a delay in the execution The following statement will pend execution until 6:15 p.m.; a statement on the next line will be executedafter this time.
many more statements here
ask_for_raise:
UPDATE salaries SET salary = @salary * 0.1This block of code will jump unconditionally to the label ask_for_raise (whichyou specify by adding a semicolon after the name), no matter where in the T-SQLprogram the block is located
This keyword has been unanimously condemned by every professional programmer — for a reason It causes a jump from the current statement to theplace in your SQL program where it finds the specified label It is easy to arguethat frequent use of this keyword greatly reduces clarity and may lead to spaghetticode — hard to read, impossible to maintain Nevertheless, I vouch for its validitywhen applied judiciously For example, if one validation fails and you wanted tobypass all other validations, and you had several such validations in your proce-dure, would it not make sense to use GOTO to go to a CLEANUP label on condition
of a failure?
Exploring T-SQL Operators
Once you’ve got variables you need tools in order to perform operations on them
SQL Server uses the following categories of operators:
Trang 14String concatenation operators
Unary operators You have been using some of them for quite a while Using bitwise operatorsrequires a thorough understanding of programming concepts and low-level com-puter operations; I will touch on this subject only briefly
Trang 15Operator Description
>= Greater than or equal to
<= Less than or equal to
<> Not equal to
! = Not equal to (SQL-89 standard)
! < Not less than (SQL-89 standard)
!> Not greater than (SQL-89 standard)
Examples of using comparison operators are shown throughout this session
Logical operators
Logical operators evaluate to true or false following the rules of Boolean algebra —they are, in fact, Boolean operators The full list of the logical operators is given inTable 10-3
OR True if either logical expression evaluates to trueSOME True if some of a set of compared values evaluates to true
Trang 16The compared values or set of compared values is evaluated based on the tors’ order of precedence.
opera-The assignment operator
Transact-SQL only has one assignment operator, and you’ve probably guessed italready — it’s the equals sign (=) You use it when assigning values to variables orspecifying column headings
The string concatenation operator
String concatenation is an operation you’ll find yourself performing over and overagain Luckily, it is very intuitive — T-SQL uses the plus sign (+) to concatenatestrings You can use it in SELECT statements like the following:
SELECT au_fname + ‘,’ + au_lname FROM authorsYou can also use it to produce console output:
DECLARE @MyString VARCHAR(40) SET @MyString = ‘concatenating’ + ‘ ‘ + ‘strings’ + ‘ is ‘ +
vari-Table 10-4
Unary Operators
Operator Description
Trang 17The following sample creates two variables, assigns an integer value to one ofthem, and assigns the negative value of the first variable to the second.
SET @Num1 = 5 SET @Num2 = -@Num2 PRINT CAST(@Num2 AS VARCHAR(2))
In Books Online you also will find the bitwise unary operator (~), which forms the logical NOT operation
per-Operator precedence
Precedence determines the order in which operators will be executed Pay special
attention to the precedence of operators when assembling complex queries,because the order of execution affects the final results Here are the operators, inorder of precedence:
+(positive), -(negative), ~(bitwise NOT)
*(multiply), /(divide), %(modulo)
+(add), +(concatenate), -(subtract)
Trang 18Working with Aggregate Functions
I used some aggregate functions earlier in this session while explaining how tocontrol flow statements The syntax and usage of the aggregate functions is fairlyintuitive The general syntax is as follows:
<function’s name> ( [ ALL | DISTINCT ] expression )
DISTINCT tells the query to ignore duplicate values, and ALL is a default(for applying the function to all values)
SUM returns the total of all the values in a numeric field, as in the ple used earlier in this session:
exam-SELECT SUM(bonus) FROM salaries
AVG returns the average of all the values in the numeric column:
SELECT AVG(bonus) FROM salaries
COUNT returns the number of records in the group:
SELECT COUNT( DISTINCT au_lname) FROM authors
COUNT(*) tells Transact-SQL to select all records fulfilling the condition
MAX returns the highest value in the column:
SELECT MAX(bonus) FROM salaries
MIN returns the lowest value in the column:
SELECT MAX(bonus) FROM salariesYou can apply aggregate functions only to numeric columns, because aggregatefunctions can accept only numeric values as arguments
Running Subqueries
I mentioned earlier that you can use subqueries in logical expressions The concept
of a subquery is really simple — it’s a query within a query, or a query within a
query within a query, and so on ad infinitum You’ll typically use subqueries when
the WHERE clause contains a selection criterion that must be calculated or selected
on the fly from a table (usually an unrelated lookup table) The following queryprepares a result set of all authors living in states wherein tax is lower than twopercent:
Trang 19SELECT * FROM authors WHERE state IN (SELECT state FROM states
WHERE tax < 2)
As you can see, the second query — the subquery, that is — returns a list of thestates wherein tax is lower than two percent, and the first query selects only thoseauthors who live in the states on this list A statement in a subquery evaluatesbefore the query: This means that states were selected before the search forauthors began If you can find a relationship between tables it is easy to rewritethe query with an equivalent JOIN statement
You can use subqueries with UPDATE, DELETE, and INSERT statements
If you can use a JOIN operation instead of a subquery, I mend using it; subqueries, though useful, are expensive in terms
recom-of system resources.
Using the CASE Function
In T-SQL the CASE function compares two or more values and returns some fined result Consider the following sample in which your boss wants a suggestionbased on overall employee performance
prede-SELECT Emp_FirstName + ‘,’ + Emp_LastName, suggestions = CASE rating
WHEN ‘excellent’ THEN ‘deserves a bonus’
WHEN ‘good’ THEN ‘needs to improve’
WHEN ‘poor’ THEN ‘ready to be fired’
ELSE ‘no suggestions’
END FROM employees
To those who program in any other language, the CASE statement
of T-SQL can be somewhat confusing It is not equivalent to the CASE you might know from C or Visual Basic, but it is similar to the IIF function For example, consider the following: variable = IIF( expression, true part, false part) In plain English, this means that if the expression yields true then the true part will
be returned; otherwise, false part is assigned to the variable.
Trang 20No restrictions exist on the number of CASE statements you can have in yourSELECT statement You can apply CASE to every field (column) you wish to return
in your result set
REVIEW
Variables are the data holders you can use in your T-SQL programs to storevarious data types; a variable must be declared of a specific type and used
to store data of this type
Some types can be converted into others implicitly, while others need to
Subqueries always execute before the parent query; use them to specifyselection criteria based on another selection
The CASE statement is a great tool for formatting returned data withoutresorting to row-by-row processing
QUIZ YOURSELF
1 Why do we need different types of data?
2 Can you share global variables between connections?
3 What is an implicit conversion? An explicit conversion?
4 How do you exit a loop construct?
5 Which operator takes the highest precedence?
6 Can you use aggregate functions on a column of the varchar data type?