Chapter 05 - Creating Database Tables and Using Datatypes![]()
![]() Data-processing systems involve the storage, processing, and retrieval of information. You must define where data will be stored before it can be processed and retrieved. All units of information, from characters to the logical definition of the entire database, can be defined through SQL Server components.
Creating TablesData in a relational database such as Microsoft SQL Server is stored in tables that are two-dimensional arrays. You'll recall from Chapter 1 that you've had experience working with tables from everyday life (such as train or bus schedules). The columns and rows of a table are already familiar to database users. Tables were chosen as the logical structure for storing data because of their familiarity to users and ease of use for retrieving, displaying, and manipulating data.You can create Microsoft SQL Server database tables with the CREATE TABLE Transact-SQL statement. You can create up to 2 billion tables in each database. The major part of the creation of a table is the definition of the datatypes for columns. The syntax for CREATE TABLE is as follows:
Enter the name of the table (table_name) following the keywords CREATE TABLE. You can use up to 30 characters to name a database object, such as a table. The column names are entered within parentheses. You define the name and type of the column by entering a column name up to 30 characters long, followed by a Transact-SQL datatype.
Optionally, you can enter the database in which the table is created, as well as an owner of the table. You'll find it more convenient to define the current database in which you're working first with a USE database-name command. After you define your current database with the USE command, all subsequent commands are performed within the database specified with the USE command.
If you don't enter the name of the owner of an object (such as a table) when you create a table, you'll be its owner. Often, tables are created from the system administrator's (sa) account, to restrict subsequent access to the tables. The owner of the database in which the table is defined is automatically granted the CREATE TABLE permission, which allows the creation of tables. The database owner or the sa can grant CREATE TABLE permission to other users so that they can create tables in the database. You don't have to grant permission to create temporary tables in a database. You can use ON segment_name to specify the segment on which the table is created. The segment must have already been created and assigned to a logical device. If you later create a non-clustered index for your table and don't specify a segment, the table and the non-clustered segment are placed in the default segment. One use you might find for defining specific segments for a table is the separation of the table information and the clustered indexes that support it. You can optimize the system by placing the table on a specific segment that's different from its non-clustered indexes. If you specify the creation of a table and its non-clustered index on different segments, SQL Server can perform queries that use the index faster. Queries that use a table's non-clustered index can be performed faster if both are located on different segments, and if the segments are on different logical devices located on different physical disks. Sets of information (such as an index and its associated table) that are stored on different physical disks can be accessed faster than a set stored on a single disk. Data can be referenced faster because the underlying operating system and disk subsystems can perform a large part of the data transfer from two physical disks simultaneously. Sets of data located on a single physical disk must be accessed separately just due to physical layout of the disk drive.
Understanding DatatypesThe major part of defining a table is specifying the datatypes for the columns of the tables. Transact-SQL allows you to define several datatypes, including those for the storage of characters, numbers, and bit patterns. You can also define your own datatypes for use in stored procedures, tables, and other work that you'll be doing with the database tables.You must define at least one column for a table, and you can define up to 250 columns. You're also limited to a maximum row length of 1,962 bytes.
You should be careful to follow the rules for relational database design whenever feasible, however, to ensure the optimum response time and use of your SQL Server engine. For more information on database design, refer to Chapter 2, "Understanding Data Modeling and Database Design" Tables are created by using a unit of measure called an extent. When you create a new table, the allocation of space for the table is initially set at one extent, which is eight pages, each of which is 2K in size. When the table fills the space in the already allocated extents, additional extents are automatically implemented up to the space allocated to the overall database size.
Creating Temporary TablesCreating a temporary table is a useful technique that you should take advantage of. You can create two types of temporary tables in SQL Server: local and global. A local temporary table is created if the first character of the table name is a pound sign (#). A local temporary table can be accessed only by the session in which it was created. A local temporary table is automatically dropped when the session in which it was created ends. You can't use more than 20 characters, including the pound sign, to name a local temporary table.You create a temporary table that can be accessed by any session (each session can be created by a different user on a different client system) by defining a table with two pound signs (##) as the first two characters of the table name. A temporary table that's accessible from multiple sessions is called a global temporary table and is automatically dropped when the last session that's using it ends.
You can use temporary tables to store sets of data that need to be operated on before permanently storing. For example, you can combine the results of the data from multiple data sets into a temporary table, and then access the combined data in the temporary table throughout your session. Data that has already been combined in a temporary table can be accessed faster than data that must be dynamically accessed from multiple tables. A temporary table that combines the results of two tables is faster to access because SQL Server doesn't need to reference the database tables to retrieve the information.
You might also find it convenient to use a temporary table to make a set of data available to a stored procedure that's invoked from another procedure. You'll find it easier to make data available to another procedure within a temporary table rather than pass data as a set of parameters.
Selecting DatatypesThe datatype is the first characteristic you define for the column of a table. The datatype of a column controls the type of information that can be stored within the column. Define the datatype by following the column name with a keyword that may also require some parameters. After you define the datatype of a table column, it's stored as a permanent characteristic and can't be changed.You can also use datatypes to define other data-storage structures, such as parameters and local variables. Parameters and local variables are storage structures defined in RAM rather than on disk. You're limited to a subset of the datatypes for the definitions of parameters and variables.
The next sections review each of the different system-defined datatypes that you can use in the definition of your SQL Server tables and stored procedures.
Numeric integer DatatypesNumeric integers are the first of several datatypes that you can use to define storage objects. Integer datatypes allow you to store whole numbers. You can directly perform arithmetic operations on integers without using functions. Numbers stored in integer datatypes always occupy the same amount of storage space, regardless of the number of digits within the allowable ranges for each the integer datatype.
The following example shows the creation of a table with three columns. The columns are defined as the int, smallint, and tinyint datatypes. A single row is inserted into the number_example table with values within the acceptable range for storage of each datatype. select is subsequently used to retrieve the row.
Enforcing Value RangesMicrosoft SQL Server automatically enforces the insertion of values within the range of each datatype. In the following two examples, values are inserted into columns that are defined as smallint and tinyint, although the values are outside the range of acceptable values.The column values are specified in the values clause of the insert statement in the same order in which the columns were defined in the table. SQL Server returns an error message that describes the reason for the failed row insertionthe attempted insertion of a value is outside the allowable range for the datatype.
Numeric floating-point DatatypesFloating-point datatypes are the second group of several numeric datatypes you can use to define storage structures such as table columns. Unlike the integer datatypes, floating-point datatypes can store decimal numbers.Unfortunately, the floating-point datatypes are subject to the rounding error. The storage of a value in a numeric datatype that's subject to the rounding error is accurate only to the number of digits of precision that's specified. For example, if the number of digits of precision is 15, a number that's larger than 15 digits can be stored, but the digits beyond 15 may inaccurately represent the initial number inserted into the storage. Also, the number may inaccurately return results of computations that involve floating-point datatypes. The rounding error affects a number's least-significant digitsthe ones at the far right. You can accurately store numbers within the number of digits of precision available in floating-point datatype.
The real DatatypeThe first of the floating-point datatypes is real, which is stored in 4 bytes. You can store positive or negative decimal numbers in the REAL datatype, with up to seven digits of precision. You can store numbers in a column defined as real within the range of 3.4E38 to 3.4E+38.The range of values and representation is actually platform-dependent. Remember that Microsoft SQL Server evolved from the original Sybase SQL Server implementation. The REAL datatype stored on each of the several computer systems that a Sybase version was written for varied in the range of allowable characters and the actual representation of characters. For example, the range of decimal numbers stored by OpenVMS on Digital's VAX computers is 0.29E to 38 to 1.7E+38. The underlying operating system that Microsoft SQL Server runs on is supported on Intel, MIPS, PowerPC, and Alpha AXP systems. You should consider the previously stated valuethe range of 3.4E38 to 3.4E+38as approximate and check the range of allowable numbers for the floating-point datatype that's stored in 4 bytes on your Windows NT system. You should also realize that data stored in floating-point datatypes, which is moved between different NT platforms with different processor architectures, may require conversion to compensate for different representations and range of values.
If you specify a value for n within the range of 1 to 7, you're actually defining a real datatype. If you specify a value within the range of 8 to 15, the datatype has the identical characteristics as if n were omitted. In the following example, a table is created with two columns defined as real and float. A single row is added with identical numbers that are subsequently added to each column of the table. The retrieval of the row from the table shows that the number stored in the real column was stored accurately to only 7 digits, the maximum number of digits of precision for a real datatype. The same 11-digit number was stored correctly in the column defined with the datatype float because float allows up to 15 digits to be stored accurately.
Use p to define the number of digits that can be stored to the left and right of the decimal point. Use s to define the number of digits to the right of the decimal point that must be equal to or less than the value of p. If you omit a value for p, it defaults to 18; the default of s is 0. Table 5.1 shows the number of bytes that are allocated for the specified precision (value of p).
The following example shows the storage and subsequent retrieval of a single row stored with the columns of a table defined as numeric/decimal datatypes. This example shows the default precision and scale and an explicit precision and scale being displayed.
Character DatatypesYou'll frequently use character datatypes to define table columns or other storage structures. Character datatypes allow the storage of a wider variety of symbols than numeric datatypes. Character datatypes enable you to store letters, numeric symbols, and special characters such as ? and >. You enter character data in either single or double quotation marks ([pr] or [dp]) when loading it into a storage area such as the column of a table.
You can define a char(n) datatype to contain up to a maximum of 255 characters. Remember, the column value always contains the specified number of characters. SQL Server automatically adds spaces to the end of a char value to fill the defined length of space.
Although the default installation of Windows NT uses the ASCII code to store character datatypes, you can install Windows NT so that UNICODE is used instead of ASCII. UNICODE stores character symbols in 16 bits (2 bytes) rather than ASCII's 1 byte. If Windows NT is defined to use UNICODE instead of ASCII, you must confirm the size of each character for character datatypes in applications such as Microsoft SQL Server.
For example, if you define the table column as varchar(15), a maximum of 15 characters can be stored in the corresponding column of each table row. However, spaces aren't added to the end of the column value until the size of each column is 15 bytes. You can use a varchar to save space if the values stored in a column are variable in size. You can also specify a varchar datatype using the keyword char varying.
Using Character DatatypesIn the following examples, a table is created with two columns defined as char and varchar datatypes. The inserted row stores only two characters in each column of the row. The first column is padded with three spaces so that it occupies 5 bytes of storage. The second column of the row isn't padded and occupies only 2 bytes of storage to store the two characters. The retrieval of the row in the example displays each column value identically, masking the underlying storage difference.
When a table column is defined using the char or varchar datatype, the maximum length is specified for all values that are later inserted into the column. SQL Server will automatically truncate (cut off) all characters that are longer than the maximum length that was defined. SQL Server doesn't notify you that's the truncation is being performed. I've created several reports that I produce with code in my application. On some columns the values line up fine, but on others, they aren't lined up. What's causing the problem?
When you use char datatypes, the fields are padded with extra spaces to fill the entire defined space for the column. These columns should appear fine on your report, depending on how you've read the values from SQL Server. If the extra spaces in the field are the problem, either use a trim statement in your query or store the data as a varchar.
If you store date and time in char or varchar (or if you store time in numeric datatypes), date and time values aren't automatically formatted in conventional ways when they're displayed.
The total storage of a datetime datatype value is 8 bytes. SQL Server uses the first 4 bytes to store the number of days after or before the base date of January 1, 1900. Values that are stored as negative numbers represent dates before the base date; positive numbers represent dates since the base date. Time is stored in the second 4 bytes as the number of milliseconds after midnight.
When you retrieve values stored in datetime, the default format for display is MMM DD YYYY hh:mmAM/PMfor example, Sep 23 1949 11:14PM. You must enclose datetime values in single quotation marks when they're used in an insert or other statement. You can enter either the date or time portion first, because SQL Server can recognize each portion and store the value correctly. You can use upper- or lowercase characters for the date and one or more spaces between the month, day, and year when you enter datetime values. If you enter time without a date, the default date is January 1, 1900. If you enter the date without the time, the default time is 12:00AM. If you omit the date and the time, the default value entered is January 1, 1900 12:00 AM. You can enter the date in several ways. Each is recognized and stored correctly by SQL Server. You can enter the date in an alphabetic format, using either an abbreviation for the month or the full name of the month. You can use or omit a comma between the day and year. If you omit the century part of the year, decades that are less than 50 are represented as 20 and those that are 50 or more are entered as 19. For example, if you insert the year 49, the complete year stored is 2049. If you enter the year as 94, the complete year stored is 1994. You must explicitly enter the century if you want a century different from the default. You must supply the century if the day is omitted from the date value. When you enter a date without a day, the default entry is the first day of the month. The set option dateformat isn't used if you specify the month of the year in alphabetic format. If you installed Microsoft SQL Server with the US_English Language option, the default order for the display of datetime values is month, day, and year. You can change the default order for the display of the date portion of a datetime value using the set dateformat command.
You can enter dates several ways, including the following examples:
The numeric format for datetime values permits the use of slashes (/), hyphens (-), and periods (.) as separators between the different time units. When you use the numeric format with a datetime value, you must specify the month, day, and year of the date portion of the value. In the numeric format, enter a separator between the month, day, and year entered in the order defined for dateformat. If you enter the values for a datetime datatype that's in the incorrect order, the month, day, or year will be misinterpreted and stored incorrectly. If you enter the information in the incorrect order, you may also receive an error message that tells you the date is out of range. The following is an example of several entries for the numeric form of the date portion of a datetime datatype value with set dateformat defined as month, day, and year and the language as US_English:
The last of the possible formats for the date portion of a datetime datatype value is unseparated four-, six-, or eight-digit values or a time value without a date value portion. The dateformat controlled through set dateformat doesn't affect datetime datatype values referenced as the unseparated digit format. If you enter a six- or eight-digit unseparated value, it's always interpreted in the order of year, month, and day. The month and day are always interpreted as two digits each. Four unseparated digit values are interpreted as the year, with the century and the month and day default to the first month and the first day of that month. Table 5.2 lists the possible interpretations of unseparated digit datetime datatype values:
When you inserted the new row, you must have used [pr][pr] as a value for the datetime column, mistakenly thinking that it would result in a null entry. When two single quotation marks are used with no characters inserted between them as the value for either of the date and time datatypes, the entry January 1, 1900, and 12 midnight is always inserted by SQL Server. You must enter the time with the time units in the following order: hours, minutes, seconds, and milliseconds. You must have a colon as a separator between multiple time units to allow a set of digits to be recognized as a time rather than a date value. You can use AM or PM, specified in upper- or lowercase, to specify before or after midnight. You can precede milliseconds with a period or a colon, which affects the interpretation of the millisecond unit. A period followed by a single digit specifies tenths of a second; two digits are interpreted as hundredths of a second; three digits are interpreted as thousandths of a second. A colon specifies that the following digits will be interpreted as thousandths of a second. Table 5.3 shows several possible interpretations of the time portion of a datetime datatype value.
The total storage of a smalldatetime datatype value is 4 bytes. SQL Server uses 2 bytes to store the number of days after the base date of January 1, 1900. Time is stored in the other 2 bytes as the number of minutes after midnight. The accuracy of the smalldatetime datatype is 1 minute. You can use smalldatetime to store values that are within its more-limited range and lesser precision when compared to datetime.
In the following example, one column is defined by using the datetime datatype, and the second column is defined using the smalldatetime datatype. After the table is created, a minimum value is inserted into each column of a single row for the respective datatypes.
Specialized DatatypesTransact-SQL contains a set of specialized datatypes for data storage. Most of the time you'll store data in more conventional datatypes such as integer, floating-point, and character. You can store dates and times in the datetime or smalldatetime datatypes.Although you'll probably find that you can use the integer, floating-point, character, and date/time datatype formats for storing 90 percent of your data, in some cases you'll probably need a more custom solution. In these cases, you can use one or more of the specialized datatypes. For example, you may need to store only data that can be represented as true or false, yes or no. Since this is a binary condition, you may decide to create a custom datatype. As another example, you may need to store sets of data in a column that's larger than the 255-character limitation of the conventional character datatypes. Several additional datatypes are available to allow you to choose the best datatype for storing your information.
You can also use a single byte to define up to eight different bit columns of a table by using the bit datatype. The amount of space allocated for one or more bits is a single byte, and the bit columns don't have to be contiguous. If you define nine columns of a table by using the bit datatype, 2 bytes are used for the total of nine bit datatypes.
The counter value inserted by SQL Server into a timestamp column specifies the sequence of operations that SQL Server has performed. Values entered into a timestamp column are stored in a varbinary(8) format, not a datetime or smalldatetime format. Null values are permitted in a timestamp column by default. A timestamp value isn't a date and time, but it's always unique within the table and database. You can define only a single column of a table as a timestamp.
Timestamps are also usedagain, as part of the where clauseto prevent two people from updating the same row. Because the timestamp is updated automatically whenever an update is made to the row, you can be sure that you're not going to overwrite someone else's information. If someone else updates a row that you're now working on, when they save their update, the row's timestamp will be updated, no longer matching your copy. When you issue the update command to save your changes, the where clause will fail because it can't find the specific row that you retrieved. Timestamps are excellent, server-maintained ways to make sure that you have a unique row identifier. If you define a column with the column name timestamp and don't specify a datatype, the column is defined using the timestamp datatype. You can display the current timestamp value that's applied to the next timestamp column of a row that's updated or to a new row added using the global system variable @@dbts.
You must enter the first binary value preceded with 0x. You can enter binary data using the characters 0 through 9 and A through F. For example, enter the value A0 by preceding it with 0x, in the form 0xA0. If you enter values greater than the length that you defined, the values are truncated. Values are also padded with zeros after the least significant digit. Here's another example. A column defined as binary(1) can store up to the maximum value of ff. In the following example, a table is defined with two columns with the datatypes binary(1) and binary(2). Three insert statements are used to enter successive pairs of values of 0, 1, ff, and fff in both columns.
Unlike the binary datatype, varbinary datatype storage is limited to just enough space for the length of the actual value. Like the binary datatype, you must enter the first binary value preceded with 0x. You can enter binary data using the characters 0 through 9 and A through F. If you enter values that are greater than the maximum length you defined, the values are truncated. In the following example, a table is defined with two columns with the varbinary(1) and varbinary(2) datatypes. Three insert statements are used to enter successive pairs of values of 0, 1, ff, and fff in both columns.
Your data is stored in fixed-length strings of characters in an initially allocated 2K (2,048 bytes) unit. Additional 2K units are dynamically added and are linked together. The 2K data pages are logicallybut not necessarily physicallycontiguous. If you use an insert statement to insert data into a column defined as text, you must enclose the data within single quotation marks.
Your data is stored in fixed-length byte strings in an initially allocated 2K (2,048 bytes) units. Additional 2K units are dynamically added and are linked together like the pages for a text column. The 2K data pages are logicallybut not necessarily physicallycontiguous.
Using text and image DatatypesValues that are stored as either text or image datatypes are displayed just as other columns are when you use a select statement. The number of bytes displayed is limited by the global value @@Textsize, which has a default value of 4K. You can specify the null characteristic for text or image columns. A null for a text or image column of a table doesn't allocate any 2K pages of storage, unless an update is performed on a row containing the null value.In the following example, two table columns are defined using image and text. Values are inserted into each column of a single row using an insert statement. The row is then retrieved from the table with a select statement.
Restrictions on text and image ColumnsYou'll encounter several restrictions on the use of data stored in text and image datatypes. You can define only table columns using the text or image datatypes. You can't define other storage structures (such as local variables or parameters) as text or image datatypes.The amount of data that can be stored in a text or image table column makes each datatype unsuitable for use or manipulation in many Transact-SQL statements. This is simply because the amount of data that would have to be manipulated is too great. You can't specify a table column in an ORDER BY, GROUP BY, or compute clause that's a text or image datatype. SQL Server won't try to sort or group a table's rows using a column that can contain more than 4 billion bytes of data because too much data would have to be moved around and too large a space would have to be allocated in which to order the rows. You also can't use a text or image column in a union unless it's a union all. You can't use a subquery that returns data values from a text or image datatype. You also can't use a text or image column in a where or having clause, unless the comparison operator like is used. You can't specify distinct followed by a table column that's defined as a text or image datatype. Finally, you can't create an index or a primary or foreign key that's defined using a table column that you've defined as an image or text datatype.
When you add values to a table column defined as money or smallmoney, you must precede the most-significant digit with a dollar sign ($) or a sign of the defined monetary unit. In the following example, a table is created with two columns that are defined using the money and smallmoney datatypes. In the first insert statements, values are incorrectly added because they aren't preceded with a dollar sign. A select statement shows that the values displayed are identical to those that were stored.
A large monetary value, which is defined as a money datatype, is added to the first column. It's incorrectly entered because it isn't preceded by a dollar sign ($). The select statements show that the number is stored incorrectly. If you enter a value into a table column that's defined as money or smallmoney, it's stored as a floating-point datatype, which makes it subject to the rounding error.
Understanding null and not nullNow that you've learned about the additional datatypes that can be defined for Transact-SQL storage structures such as columns, parameters, and local variables, you should understand a second characteristic that you can define. In addition to specifying the datatype of a table column, you can specify an additional characteristic for each datatype: null or not null.The null characteristic for a table column allows you to omit the entry of a column value in the column. If you define the characteristic for a column as not null, Microsoft SQL Server won't allow you to omit a value for the column when you insert a row. The null characteristic provides a type of validation. The default characteristic for a column is not null, which doesn't allow an undefined column value. A null that's defined for a column is stored differently than a space, a zero, or a null ASCII character (which is all zeros). The interpretation of a null entry is undefined or unavailable because no explicit or implicit value is assigned to the column when a row is inserted. If you reference a row that contains a null, the entry (null) is displayed in place of a column value to indicate that there's no entry in the row for that column. There are two ways to designate that a column or storage structure contains a null:
In the following example, a table is created that permits a null entry for numeric integer datatypes and character datatypes. A null is explicitly inserted into both columns of a single row in the table. In the following example, a select statement displays (null) for both column values of the row.
To continue the example, null is entered in the second column (y) because only the x column precedes the values clause. A null value is added to the second column y implicitly because no value is specified in the list port (values within parentheses separated by a comma) of the values clause.
ANSI Support for nullsYou can change the behavior of SQL Server to automatically permit nulls on table columns (or user-defined datatypes) if no reference to a the null characteristic is specified when a column (or user-defined datatype) is defined. You can use a set command to change the null characteristic for columns or user-defined datatypes defined during a client session. You can also change the null characteristic for an entire database using the system procedure sp_dboption.Use the following set command to cause nulls to be permitted automatically in table columns or user-defined datatypes:
However, rows that contain multiple null values in a column referenced in an ORDER BY, GROUP BY, or DISTINCT clause of a select statement are treated as identical values. All three clauses group together rows with identical values. ORDER BY is used to sort rows, and, in the case of nulls, all entries in the same column are sorted together. Columns containing nulls appear at the beginning of a sequence of rows that are sorted in ascending order. GROUP BY forms groups using identical values, and all nulls of a column are placed in a single group. The distinct keyword used in a select clause removes all duplicates from one or more column values and removes multiple null values as well. Columns that contain nulls are considered to be equal when you define an index that uses a null column.
If you perform computations with columns or other data structures that contain nulls, the computations evaluate to null. In the following example, the evaluation of the expression x=x+1 evaluates to null because the x column contains only a single row with a null defined for the x column:
Using ISNULL()ISNULL() is a system function that returns a string of characters or numbers in place of (null) when a null is encountered in a data-storage structure such as a table column. The syntax of the function is as follows:
In the following example, the second column is defined with the property identity. After two rows are added to the table, a subsequent retrieval of the table rows shows that the identity column values were generated by the identity mechanism.
Creating and Using ConstraintsConstraints are defined to provide data integrity on a table and individual columns. The create table statement allows you to create primary and foreign keys, define unique column and rows, and specify check and default constraints.
The syntax of the PRIMARY KEY constraint is as follows:
The PRIMARY KEY and FOREIGN KEY constraints ensure that corresponding rows of associated tables continue to match so that they can be used in subsequent relational joins. The automatic updating of the corresponding columns of different tables after they're defined as PRIMARY KEY and FOREIGN KEY constraints is called declarative referential integrity, a feature added to SQL Server in version 6.0. The syntax of the FOREIGN KEY constraint clause is as follows:
The process of associating a check with a table column is called binding. You can define and associate multiple checks with a single column. A check can be defined for a column, even though a rule is already defined on the column. In the following example, a check constraint is defined on the column department to restrict subsequent entries to valid departments.
You can often choose to implement a feature such as a restriction on the values that can be entered into a column in the way that you feel is the easiest to set up. For example, you can choose to restrict the values entered into the columns of a table by using a check constraint rather than by defining a rule and binding it to the column.
However, you should investigate each alternate mechanism, because one may be more appropriate for your use. Although a check constraint is quicker and simpler to set up to restrict the column values than a rule, a rule is more flexible in one way. After you define a rule, it can be bound to a column in multiple tables. A rule may prove more useful to you if you're going to use it to restrict column values on columns that are in multiple tables.
Microsoft recommends that you use a default constraint rather than a default when you've defining a default value for a column in a single table because a default constraint is stored with the table, rather than as a separate database object. If you drop a table, the constraint is automatically dropped. When a table isdeleted, a default is bound to a column of the table isn't deleted.
Niladic functions allow a system-supplied value that's information about the current user or a timestamp to be inserted when no value is specified. The ANSI niladic functions that can be used with a default constraint are current_user(), session_user(), system_user(), user(), and current_timestamp(). current_user(), session_user(), and user() return the user name stored in the database of the user issuing an insert or update. The system_user() function returns the SQL Server logon ID of the user, and the current_timestamp() function returns the date in the same form that's returned by the getdate() function.
Creating User-Defined DatatypesYou can define your own datatype, which can then be used as a datatype for a storage structure such as a table column. You always define a user-defined datatype as one of the existing system datatypes. A user-defined datatype allows you to define a datatype that can contain a length specification, if necessary, and a null characteristic.You can use a descriptive name for the user-defined datatype that describes the type of data that it contains.
Creating User-Defined Datatypes with sp_addtypeYou can define a user-defined datatype with the system procedure sp_addtype, which uses the following syntax:
An error message is generated if you specify not null for a column and don't create a default, or specify a value at insertion. You can also change the null or not null characteristic for a user-defined datatype when you define a column in a table. In the following example, a user-defined datatype is created by using sp_addtype. The characteristics are displayed with sp_help. A new table is created in which the column is defined using the user-defined datatype.
Creating User-Defined Datatypes with the Enterprise ManagerTo define a user-defined datatype by using the Enterprise Manager, follow these steps:
Fig. 5.1 - You can list the user-defined datatypes from the Manage User-Defined Datatypes dialog box.
Dropping User-Defined DatatypesYou can use the system procedure sp_droptype to remove a user-defined datatype. The procedure uses the following syntax:
Working with DatatypesYou can't name objects with names of commands or other reserved works because datatypes are objects in the database. Datatypes are stored in the Systypes system table along with their coded values. You can use the following select statement to display the datatypes and their code value in the type column:
Creating Tables and Defining Columns Through the Enterprise ManagerIn addition to creating a table with the create table statement, you can create a table through the Enterprise Manager. To do so, follow these steps:
You also can define properties on columns such as an identity, primary key, or constraint by clicking the Advanced Features tool on the toolbar of the Manage Tables window while you're defining the table. For example, in figure 5.4, a column has been defined as an identity column in the Identity Column combo box of the Manage Tables window after the Advanced Features tool is clicked. Fig. 5.4 - You can specify an initial value (seed) and increment for your identity column.
Adding Data to a Table with insertAfter you create a table, you can add data by using an insert statement. Several forms of the insert statement can be used to add new rows to a table. Each insert statement can add only a single row to a table. The complete form of the insert statement uses the following syntax:
You don't have to list the columns and their values in the same order as they were defined in the table. You must, however, enter the values in the VALUES clause in the correct order as the column names listed in the previous line; otherwise, data values may be inserted into the wrong columns. In the following example, the columns are listed in the order in which they were defined in the tablebut they don't have to follow the same order. The values are entered in the VALUES clause in an order that corresponds to the order of the columns named in the previous line.
From Here...In this chapter you've learned to create database tables. The process of creating a table involves the selection of the appropriate datatypes for your table columns. In addition, you've learned to add the additional characteristics that can be defined for a table column including the null characteristic and the various constraints. You learned to create, drop, and list the characteritics of a table using Transact-SQL syntax and the Enterprise Manager.For further discussion about topics mentioned in this chapter, see the following chapters:
|