Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 71 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
71
Dung lượng
0,99 MB
Nội dung
Microsoft SQL Server 2000 Programming by Example 56 The command(s) completed successfully. The UNIQUEIDENTIFIER data type has an associated system function, NEWID, that generates new values for these data types. Therefore, if you use the UNIQUEIDENTIFIER data type in a table, you can use the NEWID system function as the column's default value, as Listing 2.15 shows. Listing 2.15 Using the NEWID System Function USE Northwind CREATE TABLE Bigidentifiers ( col1 UNIQUEIDENTIFIER DEFAULT NEWID() ) GO The command(s) completed successfully. The new SQL_VARIANT data type can store up to 8,016 bytes of almost any base data type. Listing 2.16 shows how to use the SQL_VARIANT with character and integer data. Listing 2.16 Using the SQL_VARIANT Data Type USE Northwind DECLARE @integer_data SQL_VARIANT, @char_data SQL_VARIANT Chapter 2. Elements of Transact-SQL 57 SET @integer_data = 845 SET @char_data = 'This is character data' GO The command(s) completed successfully. The TIMESTAMP data type is not related at all to DATETIME or SMALLDATETIME. Moreover, you cannot directly update a TIMESTAMP column because it updates itself when you insert or update a row that contains a TIMESTAMP. Also, there can be only one TIMESTAMP column per table. Creating Customized Data Types: User-Defined Data Types Users can create their own data types using the data types provided by Transact-SQL as the base types. To create user-defined data types, or UDDT, use the sp_addtype system stored procedure, and to drop them, use sp_droptype. The basic syntax of the sp_addtype system stored procedure is sp_addtype uddt_name, uddt_base_type, nullability For example, suppose that you want to create a UDDT to store phone numbers that could be null. You can define this user-defined data type using the CHAR data type as the base type with a length of 12, as shown in Listing 2.17. Listing 2.17 Creating User-Defined Data Types (UDDTs) USE Northwind EXEC sp_addtype phone_number,'CHAR(12)',NULL GO 1 row(s) affected) Type added. Information about user-defined data types is stored in the systypes system table, which is located in all databases. When created, the properties of user-defined data types can be displayed using the sp_help Microsoft SQL Server 2000 Programming by Example 58 system stored procedure, which receives an object name as a parameter, which, in this case, would be the name of the user-defined data type, as shown in Listing 2.18. Listing 2.18 Using sp_help to Display UDDT's Properties USE Northwind EXEC sp_help phone_number GO Type_name Storage_type Length Prec Scale Nullable Default_name Rule_name phone_number char 12 12 NULL yes none none Tip UDDTs are stored in the database where they are created. However, if you want all your user databases to have a set of predefined, user-defined data types when they're created, create these UDDT in the model database. This is because every new database that is created in SQL Server is a copy of the model database. Listing 2.19 creates a UDDT called ssn in Model. This UDDT will be automatically transferred to every user database that is created afterward. Listing 2.19 Creating UDDTs in Model USE Model EXEC sp_addtype ssn,'CHAR(11)','NOT NULL' Chapter 2. Elements of Transact-SQL 59 GO 1 row(s) affected) Type added. UDDTs can be created also in Enterprise Manager. To accomplish this, right-click User Defined Data Types (which is located inside the database folder) and then choose New User-Defined Data Type, which opens the window shown in Figure 2.1. Figure 2.1. Creating UDDTs in Enterprise Manager. Data Type Selection Criteria You should be very careful when choosing data types. Always make sure that the data type you're choosing is the correct one and the length is appropriate, because it is very common to choose data types that are oversized. For example, let's say that you choose VARCHAR(100) as the data type and length for a ZIP code column. Although VARCHAR(100) is able to store this kind of data, you will waste a lot of space because ZIP codes have only five characters. In a small table, this isn't a problem, but in big tables this can lead to performance problems. The same rule applies for integer data. Take a look at the maximum and minimum value of each integer data type when choosing among them. This way, you avoid using a big data type when you could have used a smaller one. For example, a very efficient way to store IP addresses in a table is to use four TINYINT columns, because this data type can store integers from 0 to 255. If the length is not specified when declaring character (CHAR, NCHAR, VARCHAR, and NVARCHAR) or binary (BINARY and VARBINARY) data, SQL Server uses 1 as the length by default. Listing 2.20 shows the Microsoft SQL Server 2000 Programming by Example 60 declaration of a variable in which you will be able to store just one character because the length was not specified. Notice that although you don't get an error if you assign more than one character to the variable, SQL Server stores only the first character. Listing 2.20 Using the Default Length with Character Data USE Northwind DECLARE @onecharacter VARCHAR SET @onecharacter = 'String' SELECT @onecharacter GO S (1 row(s) affected) Be aware that fixed-length data types always use the length you defined. On the other hand, variable-length data types use only the actual space that is being used by the value. For example, look at the table shown in Listing 2.21. If you insert a row and the length of the lastname is 5, SQL Server will use just 5 bytes for the storage of this value because the data type is VARCHAR. On the other hand, if the length of the firstname is 5, SQL Server has to use 20 bytes to store this value because the data type is CHAR. Therefore, when using the CHAR data type, even if the length of the value is less than the length of the column, SQL Server uses the length of the whole column to store this value. Listing 2.21 Using Variable- and Fixed-Length Character Data USE Northwind CREATE TABLE Authors ( lastname VARCHAR(20), firstname CHAR(20) ) GO Chapter 2. Elements of Transact-SQL 61 The command(s) completed successfully. If you want to store data that can hold more than 8,000 bytes, use the TEXT, NTEXT, or IMAGE data types, which can store up to 2GB. However, make sure that you really need to store more than 8,000 bytes, because these data types use another set of statements (WRITETEXT, READTEXT, and UPDATETEXT). Tip You can use standard DML commands with TEXT, NTEXT, and IMAGE data, but only a portion of the data can be accessed (using the SUBSTRING function, for example). Be careful when you use approximate numeric data because, by definition, these data types (FLOAT and REAL) store an approximation of the number. Therefore, they should not be used to perform exact comparisons in WHERE clauses. The TABLE data type cannot be used as a column data type when creating tables; thus, it is not possible to have tables inside tables. Whenever possible, use the TABLE data type instead of temporary tables because the first one is stored in memory, improving performance considerably. Usually, the TABLE data type is used to store temporary result sets, as shown in Listing 2.22, in which a variable is created using the TABLE data type and then two rows are inserted. Listing 2.22 Using the TABLE Data Type USE Northwind DECLARE @Authors TABLE(lastname VARCHAR(20), firstname VARCHAR(20)) INSERT @Authors VALUES ('Guerrero','Fernando') INSERT @Authors VALUES ('Rojas','Carlos') SELECT * FROM @Authors GO Microsoft SQL Server 2000 Programming by Example 62 (1 row(s) affected) (1 row(s) affected) lastlame firstname Guerrero Fernando Rojas Carlos (2 row(s) affected) Although TIMESTAMP and ROWVERSION are synonyms, you should use ROWVERSION instead of TIMESTAMP, because Microsoft could change the functionality of TIMESTAMP in the future to be compliant with the ANSI SQL-92 standard, which states that the TIMESTAMP data type stores date and time data. Additional Elements In addition to DDL, DML, DCL, and data types, Transact-SQL has some additional elements or extensions that make life easier for programmers and administrators, and also make Transact-SQL a more powerful language. Be aware that these extensions are not ANSI-SQL standard; therefore, they are not portable. If you are concerned about portability, you should avoid using any of these extensions. SQL Server is not the only relational database management system that adds new elements to the standard language; this is done by the majority of the commercial database systems today. If you want to check that your code is compliant with the ANSI standard, use the SET FIPS_FLAGGER statement provided by SQL Server, which receives as a parameter the level of compliance that you want to check: ENTRY, INTERMEDIATE, or FULL. Listing 2.23 shows how this statement is used to check the compliance of a query that contains the TOP clause, which is a Transact-SQL extension. Listing 2.23 Using the SET FIPS_FLAGGER Statement to Check for ANSI Compliance USE Northwind SET FIPS_FLAGGER 'FULL' SELECT TOP 3 lastname FROM Employees ORDER BY hiredate GO Chapter 2. Elements of Transact-SQL 63 FIPS Warning: Line 1 has the non-ANSI statement 'USE'. FIPS Warning: Line 3 has the non-ANSI statement 'SET'. FIPS Warning: Line 5 has the non-ANSI clause 'TOP'. lastname Leverling Davolio Fuller To deactivate the checking of the ANSI compliance (because it remains activated for the session), use the same statement (SET FIPS_FLAGGER) with the OFF parameter; that is, SET FIPS_FLAGGER OFF. Variables In Transact-SQL, local variables are used in stored procedures, user-defined functions, triggers, and user scripts. Variables are valid in the session that created them; for example, if a stored procedure creates a variable, it is valid only during the execution of the stored procedure. Variables are first declared, using the DECLARE statement and specifying the variables'name (which has to begin with @) and data type. The syntax is DECLARE @variable_name datatype Then, a value is set to the variable using either SET or SELECT. When a variable is declared, its value is initialized to NULL until a value is assigned. Listing 2.24 shows the creation of the @firstname variable, which uses the VARCHAR data type with a length of 20. Next, its value is set using the SET statement, and finally, its value is shown using the SELECT statement. Listing 2.24 Using Variables in Transact-SQL DECLARE @firstname VARCHAR(20) SET @firstname = 'Maria' SELECT @firstname GO Microsoft SQL Server 2000 Programming by Example 64 Maria You can also assign values to variables in a query. Using this approach, make sure that the query returns only one row because, otherwise, you will get just one value in the variable. For example, Listing 2.25 demonstrates how to assign variables (@ln and @fn) in a query to the Employees table. This query stores the value of the first and last name of the employee whose ID equals 1 in the @fn and @ln variables. Then, it shows the value that was assigned to each one of these variables. Listing 2.25 Assigning Values to Variables in Queries USE Northwind DECLARE @ln VARCHAR(20), @fn VARCHAR(20) SELECT @ln = lastname, @fn = firstname FROM Employees WHERE employeeid = 1 SELECT @fn, @ln GO Nancy Davolio System functions that begin with @@ used to be called global variables. In fact, they are system functions that don't have any parameters, and they are not global variables because you cannot declare and assign a value to them; they are managed by SQL Server instead. Table 2.3 lists some of these system functions and the value they return. Table 2.3. System Functions That Begin with @@ System Function Return Value @@CONNECTIONS Number of connections to SQL Server since the service was started. @@ERROR Error code of the last statement executed (if it succeeded, it returns 0). @@IDENTITY Last identity value inserted in the current session. @@MAX_CONNECTIONS Maximum number of connections allowed. Chapter 2. Elements of Transact-SQL 65 @@OPTIONS Information about set options in the current session. @@ROWCOUNT Number of rows affected by the last statement executed. @@SERVERNAME Name of the server where SQL Server is installed. @@SPID ID of the current process. @@VERSION Current version of SQL Server. For example, Listing 2.26 shows how to use these system functions, specifically @@servername (the name of this server is SQLBYEXAMPLE). Listing 2.26 Using System Functions SELECT @@servername GO SQLBYEXAMPLE Caution There are no global variables in SQL Server. The @@ prefix is used just by SQL Server's system functions. Although you can declare variables using the @@ prefix, they won't behave as global variables; they will behave just as local ones. Operators Operators are used in Transact-SQL to deal with variables, scalars, and, in general, expressions. There are different kinds of operators, and each kind is used to manipulate different kinds of data types. The assignment operator is the equal sign (=). It is used to set values to variables, as shown in the preceding section (see Listings 2.24 and 2.25). The arithmetic operators are + (addition), – (subtraction), * (multiplication), / (division), and % (modulo or remainder of division). These operators are used to work with integers, approximate numeric, and exact numeric. The + and – operators also behave as unary operators (positive and negative), which deal with only one expression. In Listing 2.27, you can see an example of the use of the division and modulo operators and the negative unary operator. Listing 2.27 Using Arithmetic Operators [...]... 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18... Listing 2. 42 shows an example of both kinds of comments that can be used in Transact -SQL Listing 2. 42 Inserting Comments in the Code /* This is an example of the use of comments in Transact -SQL */ SELECT @@version this query shows the current version of SQL Server GO Microsoft SQL Server 20 00 - 8.00.194 (Intel X86) Aug 6 20 00 00:57:48 Copyright (c) 1988 -20 00 Microsoft. .. "Optimizing Access to Data: Indexes," for more information on data storage Figure 3.1 Data storage in SQL Server: pages and extents Types of Tables In versions of SQL Serverprior to SQL Server 20 00, there were only two types of tables:permanent and temporary The TABLE data type is a new feature of SQL Server 20 00 that we can add to our set of tools Note Generally, for simplicity, permanent tables are just... 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 20 00- 04-18 01:51:58.910 (19 row(s) affected) Temporary Tables Temporary tables, like any other temporary object in SQL Server, are stored in tempdb and dropped automatically by SQL Server if they are not dropped explicitly This type of table is used as a temporary working area for... which is used to concatenate strings, as shown in Listing 2. 34 Listing 2. 34 Using the String-Concatenation Operator DECLARE @first VARCHAR(10), @second VARCHAR(10) SET @first = 'SQL ' SET @second = 'Server' SELECT @first + @second GO SQL Server Generally, + is used to concatenate columns when querying tables, as Listing 2. 35 shows Listing 2. 35 Using the String-Concatenation Operator to Concatenate... Figure 2. 2 Figure 2. 2 Generating scripts in Enterprise Manager The GO Statement The GO statement is used to separate batches Even though it is not a Transact -SQL element; it is used just by the SQL Server utilities Actually, it can be changed in the Query Analyzer to any other word, if you go to the Options menu and then to the Connections tab This tab appears in Figure 2. 3 Figure 2. 3 Changing the batch... in a database; every time the view is queried, SQL Server reads its definition and uses this definition to access the underlying table Views add a layer between applications and tables because, through views, applications don't have to query tables directly In previous versions of SQL Server, a view never stored data Now, using a new feature of SQL Server 20 00 called indexed views, youcan create indexes... connections in SQL Server Therefore, when a connection creates a global temporary table, and other connections reference the table, they will be accessing the same table Global temporary tables last until the connection that created them finishes its execution Table Variables In previous versions of SQL Server, temporary tables were the only way to store temporary data or result sets In SQL Server 20 00, the... VARCHAR(30) ) In SQL Server, a table can have up to 1, 024 columns and a database can contain up to 2, 147,483,647 objects, including tables As you already know, the maximum size of a row in a table is 8,060 bytes Nonetheless, you can still create tables that have columns of variable data types (VARCHAR, NVARCHAR, and VARBINARY) whose row size exceeds 8,060 bytes In these cases, SQL Server creates the... WAITFOR indicates SQL Server to wait a specific amount of time WAITFOR DELAY 'time' Listing 2. 38 shows an example of each of these two approaches The first WAITFOR statement waits until 8:00 a.m., and the second one waits until 1 minute after 8:00 a.m Listing 2. 38 Using WAITFOR WAITFOR TIME '08:00:00' PRINT getdate() WAITFOR DELAY '00:01:00' PRINT getdate() GO Jan 9 20 01 8:00AM J9n 9 20 01 8:01AM WHILE . NVARCHAR) or binary (BINARY and VARBINARY) data, SQL Server uses 1 as the length by default. Listing 2. 20 shows the Microsoft SQL Server 20 00 Programming by Example 60 declaration of a variable. @@servername (the name of this server is SQLBYEXAMPLE). Listing 2. 26 Using System Functions SELECT @@servername GO SQLBYEXAMPLE Caution There are no global variables in SQL Server. . Listing 2. 24 Using Variables in Transact -SQL DECLARE @firstname VARCHAR (20 ) SET @firstname = 'Maria' SELECT @firstname GO Microsoft SQL Server 20 00 Programming by Example