1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft SQL Server 2000 Weekend Crash Course phần 4 potx

41 249 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 41
Dung lượng 430,85 KB

Nội dung

You need to specify fields’ names and data types as well as whether certain columns 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 Query Analyzer to create it, there is a lot of room for improvement: You can specify a FOREIGN KEY, an index, computed fields, constraints, rules, default values, and more. These features will be covered in sessions 10, 16, and 26. The table created with the preceding statement is stored permanently in your database 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 can create 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 of visibility: Local tables are accessible only to the connection in which they were created, 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 two characters of the table name, as in ##MyTable . Both local and global temporary tables are physically created in the TempDB database. Altering tables To modify an existing table you can use the ALTER statement. With the following statement 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 are bound to the table. For the complete syntax, consult Books Online. Session 9—T-SQL and SQL Query Analyzer 101 Part II—Saturday Morning Session 9 154840-9 ch09.F 8/28/01 12:53 PM Page 101 Deleting tables Deleting a table is just as easy as deleting an entire database: DROP TABLE MyTable Temporary tables have a different life span from regular tables: If a temporary table 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 to retrieve some important information about it. You can type these statements directly 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 many more. ¼ SELECT ←NGUAGE displays the name of your SQL Server language. ¼ SELECT @@SERVERNAME displays the name of the SQL Server for the cur- rent connection. ¼ SELECT @@VERSION displays information about Microsoft SQL Server — version, build, edition, and so on. ¼ SELECT @@TRANCOUNT displays the number of open transactions for the current connection. ¼ SELECT @@ERROR displays an error number giving you a clue about the source of an error and the reason it occurred. I’ll discuss SELECT@@TRANCOUNT in greater detail in Session 14. Cross-Ref Saturday Morning102 154840-9 ch09.F 8/28/01 12:53 PM Page 102 Figure 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 cre- ating T-SQL programs. The templates are canned T-SQL framework solutions that you can modify for your own use. You can get to the Templates dialog either from the 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. The Object Browser (see Figure 9-4) is another important feature provided to make your life easier. In addition to the Templates browser it also includes a full list of supported T-SQL functions and all supported system data types. The Object Session 9—T-SQL and SQL Query Analyzer 103 Part II—Saturday Morning Session 9 154840-9 ch09.F 8/28/01 12:53 PM Page 103 Browser also provides a full description of the functions and their accepted para- 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 new pane. To do this, select the appropriate option from the right-click menu — it sure does reduce the amount of typing you have to do. Figure 9-4 SQL Server’s Object Browser and templates. REVIEW ¼ SQL Query Analyzer enables you to execute T-SQL queries directly against SQL Server and analyze the results. ¼ You can use T-SQL to create, modify, and delete various objects in SQL Server 2000, such as databases and tables. Saturday Morning104 154840-9 ch09.F 8/28/01 12:53 PM Page 104 ¼ SQL Server 2000 contains a vast collection of system functions that you can use in your T-SQL code to perform specific tasks and retrieve system properties. ¼ Query Analyzer templates and the Object Browser provide you with an easy way to locate and use specific system functions, and reduce the amount of typing 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? Session 9—T-SQL and SQL Query Analyzer 105 Part II—Saturday Morning Session 9 154840-9 ch09.F 8/28/01 12:53 PM Page 105 154840-9 ch09.F 8/28/01 12:53 PM Page 106 Session 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 T his session is about programming SQL Server 2000 using its own built-in lan- guage, Transact-SQL. You will learn how to produce working programs using T-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. A variable is a conceptual placeholder that can contain data and to which you, the programmer, can assign these data at will. Until a value is assigned to the variable, SESSION Programming with T-SQL 10 164840-9 ch10.F 8/28/01 12:53 PM Page 107 the 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 may find 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 can- not share variables between connections. See Session 11 for a discussion of stored procedures. The main function of variables is to store intermediate data, keep a counter for the 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. If the table contains more than one record in which the last name of the person is Carson, 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 Saturday Morning108 164840-9 ch10.F 8/28/01 12:53 PM Page 108 database, returns two records in ascending alphabetical order (the default): first ‘Albert’ and then ‘Anne’. SELECT au_fname FROM authors WHERE au_lname = ‘Ringer’ The query SELECT @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 the correct data type in order to prevent errors. When dealing with financial data you may 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 processing and 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. Implicit conversion Implicit conversion is taken care of by SQL Server itself. It occurs either when a variable of one data type is assigned to another variable of a compatible data type, or when an operation, such as comparison, requires both variables to be of the same type. In either case you must understand the potential ramifications of an implicit conversion, which might introduce subtle, hard-to-catch bugs into your T-SQL program. Consider a situation wherein you have two variables, one of the float type and another of the integer type. The float-type variable holds a value representing your account, with all cents represented as digits after the decimal point, as follows: 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 gone forever if you use @IntermediateHolder for future calculations. Session 10—Programming with T-SQL 109 Part II—Saturday Morning Session 10 164840-9 ch10.F 8/28/01 12:53 PM Page 109 Explicit conversion In order to convert from one type to another you need to use the special conver- sion functions CAST and CONVERT. These functions behave similarly, but CAST is preferable to CONVERT: It complies with SQL-92 standards, so you can use it when porting your SQL code to other vendors’ products. CAST ( expression AS data_type ) CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) Here are some examples of explicit conversion. If for some reason you want to convert 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 char- acter string into numbers. Consider the following: The ZIP field is of the varchar type and you cannot do arithmetic with characters, but you need to add up all the ZIP codes from the Authors table — your boss requires it for his astrological research. You can do this using CAST and the aggregate function SUM (covered later in this session). The result, by the way, is 1,904,317. The following query using CONVERT will produce exactly the same result. You do not have to specify the length of the data for the basic type, as it is implied by default. 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 from Microsoft SQL Server Books Online, specifies which data types can be converted to which others — implicitly or explicitly. Saturday Morning110 164840-9 ch10.F 8/28/01 12:53 PM Page 110 [...]... T -SQL? 13 What is the T -SQL syntax for deleting a database? 14 Which databases cannot be deleted from SQL Server? 15 How are SQL Server databases physically stored under Windows 2000? 16 What is the internal language of SQL Server 2000? 17 How do you execute T -SQL statements? 18 What is a variable? How do you declare one? 19 What value could be assigned to VARCHAR datatype 1 748 40-9 pr2.F 8/28/01 122... every SQL Server installation? 6 What is the purpose of the Master database in SQL Server? 7 Which SQL Server system database is a template database? 8 How do you resolve many-to-many relationships in RDBMS? 9 What is data normalization? 10 What is the purpose of the first normal form? 11 What components must you define for every database created in SQL Server? 12 How do you create a database with T -SQL? ... are the four basic queries in SQL? 21 What are the main control-of-flow T -SQL constructs? 22 What are the different types of joins and what do they do? 1 748 40-9 pr2.F 8/28/01 12:53 PM Page 123 1 848 40-9 po3.F 8/28/01 12:53 PM Page 1 24 PART III Saturday Afternoon Session 11 Creating and Using Stored Procedures Session 12 Trigger Happy Session 13 Introducing Cursors Session 14 Understanding Indexes Session... 12 (it is limited by datasize restriction), but it serves to illustrate the principle Note A stored procedure written in T -SQL has all the strengths and weaknesses of SQL itself Sometime you need to access functionality beyond what is provided by SQL Server and T -SQL Microsoft SQL Server enables you to invoke an extended stored procedure implemented as a Dynamic Linked Library (DLL), usually in C/C++... procedures System stored procedures Microsoft SQL Server 2000 uses stored procedures extensively: It comes with a number of precompiled system stored procedures to assist you in performing various tasks that are difficult or dangerous to perform directly (such as querying system tables) The system stored procedures are stored in the Master database Microsoft SQL Server 2000 comes with 930 canned system... 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: ¼ Arithmetic operators ¼ Comparison operators ¼ Logical operators ¼ Assignment operators Part II—Saturday Morning Session 10 WAITFOR DELAY ‘000:00:05’ 1 648 40-9 ch10.F 8/28/01 12:53 PM Page 1 14 1 14 Saturday Morning ¼ String concatenation... (custom error message OR error message ID, severity level, state, [argument ( n)], WITH [options ]) 1 948 40-9 ch11.F 8/28/01 12:53 PM Page 132 132 Saturday Afternoon Note Keep in mind that every application that accesses data in SQL server goes through layers of connectivity interfaces provided with SQL Server Each layer may raise its own errors, such as OLE DB Provider, ODBC Driver, Enterprise Manager,... temporary stored procedure exists as long as the current SQL Server session Once the server is restarted all temporary stored procedures are gone 1 948 40-9 ch11.F 8/28/01 12:53 PM Page 133 Session 11—Creating and Using Stored Procedures 133 Nested and recursive stored procedures CREATE PROCEDURE usp_FindFactorial ( @Number int, @Result int ) AS e.g 5! = 5 * 4 * 3 * 2 * 1 multiply result SET @Result = @Result... Understanding Transactions and Locks 1 948 40-9 ch11.F 8/28/01 12:53 PM Page 125 SESSION 11 Creating and Using Stored Procedures Session Checklist ✔ Creating stored procedures ✔ Commenting Transact -SQL code ✔ Handling errors ✔ Using different types of stored procedures ✔ Renaming and dropping stored procedures M icrosoft SQL Server enables you to store compiled T -SQL statements as a special database object... SELECT @count_authors=COUNT(*) FROM authors where state = @state RETURN 0 1 948 40-9 ch11.F 8/28/01 12:53 PM Page 130 130 Saturday Afternoon How do you know that an exception had occurred in your program — before the computer crashes, that is? Whenever your T -SQL code executes you can inquire about errors using the @@ERROR SQL Server function shown in the next example (0 indicates an error-free state): . modify, and delete various objects in SQL Server 2000, such as databases and tables. Saturday Morning1 04 1 548 40-9 ch09.F 8/28/01 12:53 PM Page 1 04 ¼ SQL Server 2000 contains a vast collection of. Figure 9 -4 SQL Server s Object Browser and templates. REVIEW ¼ SQL Query Analyzer enables you to execute T -SQL queries directly against SQL Server and analyze the results. ¼ You can use T -SQL to. name of your SQL Server language. ¼ SELECT @@SERVERNAME displays the name of the SQL Server for the cur- rent connection. ¼ SELECT @@VERSION displays information about Microsoft SQL Server — version,

Ngày đăng: 13/08/2014, 22:21

TỪ KHÓA LIÊN QUAN