Você está na página 1de 10

FBE Computer Science Dept

130999249.doc

Mekelle University Faculty of Business & Economics Computer Science Department Comp 221: Database with SQL Server Handout 6 Advanced Data Types, Date-time Functions, Views

RECOMMENDED TEXTS: Ref A: SQL Server 2000 The Complete Reference Jeffrey R. Shapiro, Osborne McGraw Hill

1 Overview This handout deals with some miscellaneous SQL topics. It covers some more advanced data types to supplement the basic types already covered as well as functions that can be used to work with date-time values. It also covers views and stored procedures. 2 Advanced Data Types Type Full name (from SQL-92 standard)
Decimal (p,s) Numeric (p,s) decimal

Description
Precision and scale values up to 38 digits long i.e. from (10^38) + 1 to (10^38) 1; p is precision this is the max total number of digits in the number, including those to the right and left of the decimal max value is 38. s is scale this is the max number of decimal digits that can be stored to the right of the decimal must be a value from 0 to p; default is 0. For example: decimal (7,2) would be a number with up to 7 digits, with 0,1 or 2 digits after the decimal point. Variable length character data, maximum length is (2^31) 1 characters; this is useful for storing large pieces of text in a database field. Variable length binary data, maximum length is (2^31) 1 bytes; Fixed-length Unicode* data where the maximum length is n characters, n is in the range 1 to 4000. Page 1 of 10

Storage size
1-9 = 5 bytes 10-19 = 9 bytes 20-28 = 13 bytes 29-38 = 17 bytes

Text

Not a SQL92/99 data type specific to SQL Server Not a SQL92/99 data type specific to SQL Server National character

A byte per character

Image nchar (n)

As many bytes as are stored in the field 2 * n bytes (8000 bytes maximum)

FBE Computer Science Dept

130999249.doc

varchar(n)

National character varying

ntext

If n is not specified, the default is 1. Variable-length Unicode data where the maximum length is n; n must be in the range 1 to 4000. If n is not specified, the default is 1. Variable length Unicode data, maximum length is (2^30) 1 characters.

Depends on the number of characters entered (1 character = 2 bytes) 2 times the number of characters entered

* see following section about ASCII and Unicode data. 3 ASCII and Unicode Data Usually, character data is stored as ASCII (American Standard Code for Information Interchange) characters. In ASCII, each character uses 1 byte of space. ASCII is an 8 bit system, so it can support only 256 different characters. This means that if different languages or alphabets are to be supported, each one needs a different encoding specification (called a code page) programmes such as SQL Server use the code page to interpret bits into character data. Code pages are used because 256 is not enough characters to support multiple character sets. The drawbacks of storing data in ASCII format are that some characters may have different bit patterns on different code pages and that some characters may appear on one code page but not on another. In this case, when data is transferred between systems that have different code pages, the data must be converted from the code page of the source system to that of the receiving system. Even with the conversion, some character data may change or there may be unknown characters. This can be a problem when building a system, e.g. a database, that must support multiple languages. This is also more of a problem for internet applications, where there may be many different clients receiving data from a central system. This problem has been addressed by the use of the Unicode Character System (UCS). This system uses 2 bytes for each character this allows for 65,356 different bit patterns, which is sufficient to cover all major business languages. If the character data in a system is stored using Unicode, and it is transferred to another system that uses Unicode, then there will be no conversion problems such as loss of data. In SQL Server, the char, varchar and text data types store characters in ASCII format. SQL Server has 'collations' a collation includes the code page to use, as well as sort orders for character data. The collation can be specified for the database server but can also be set at the database level and for individual columns in tables. The nchar, nvarchar and ntext data types store characters in the Unicode format. This means that twice as many bytes are required to store values of these types, as for the char, varchar and text equivalents. However, if the system is being used to store data in many languages, or if the data may be exported to other systems, then it is worth using the nchar, nvarchar and ntext types.

Page 2 of 10

FBE Computer Science Dept

130999249.doc

Therefore, the national character types (nchar, nvarchar, ntext) should be used in systems where many languages or alphabets are being used or where data may need to be transferred to other systems. 1.1 Unicode and Geez In the year 2000, the Unicode Consortium (a non-profit making body that maintains the Unicode Standard) allocated a range of codes for the Geez script (from U+1200 U+137F). The Visual Geez Unicode software package can be installed on a PC and then used to enter data in the Geez Unicode. It provides a font for Geez and encodes the characters using the Unicode codes. In theory, this means that problems of transferring Geez data between applications and operating systems are eliminated (before this, different systems would have had different encoding sets for Geez characters). However, this does require that software applications have incorporated the updated Unicode encoding set. SQL Server 2000 allows the Visual Geez font to be used e.g. as the Editor text in the Query Analyzer, so Geez data can be inserted to nchar or nvarchar fields. But it does not have the Unicode encoding for Geez characters. This means that the characters are displayed as unknown characters (denoted by a question mark - ?) when the values are selected from a table. It is likely that Microsoft will incorporate the latest Unicode encoding into SQL Server, through a Service Pack for SQL Server 2000 and in the next version of SQL Server. 4 DateTime Functions

The DateTime data type in SQL Server stores a data as a full date and time value. If you do not specify the time, the date is stored with a time of 00:00:00. There are a number of functions available for dealing with date-time values in SQL Server. These specific functions are not SQL92/99 standard, but you will find similar functions in other DBMS applications. The SQL Server functions are listed in the table below. Function
GetDate()

Description
Returns the current system date and time, in the SQL Server internal format

Examples
Select getdate() This would return the current date and time e.g. 2003-12-31 11:04:35.680 - the internal format uses yyyymm-dd for the date part and hh:mm:ss.ms for the time part (24 hour clock) To add one year to the current date: Select Dateadd(yy, 1, getdate()) If today is 31st December 2003, then this will return 31st December 2004. To show a list of titles and their

DateAdd (datepart, number, date)

Adds a specified interval to a date, and returns a new datetime value to reflect the addition. Datepart can be any of the following and there are abbreviations that can be used for each e.g. yy or yyyy for Year: Year (yy, yyyy) Quarter (qq, q) Page 3 of 10

FBE Computer Science Dept

130999249.doc

DateDiff (datepart, startdate, enddate)

DatePart (datepart, date)

Month (mm, m) Dayofyear (dy, y) Day (dd, d) Week (wk, ww) Hour (hh) Minute (mi, n) Second (ss, s) Millisecond (ms) Returns the difference between two dates. The difference can be calculated on any part of a date year, quarter, month etc (as listed for the Date Parts in DateAdd above). The datepart parameter specifies the part on which to calculate the difference e.g. to get the difference in days, months, weeks or years etc. The startdate value is subtracted from the enddate value so if the startdate is later than the enddate, a negative value is returned. Returns an integer representing the specified datepart of the specified date. The datepart can be any of the values listed for the datepart for DateAdd, with the addition of: WeekDay (dw) Using dw as the datepart returns an integer from 1 to 7 normally, 1 is Sunday and 7 is Saturday. To check what setting is on the server, run - this will return a number from 1 to 7 if it is 1, then the first day of a week is Monday, if it is 7 then the first day of a week is Sunday etc. To set the datefirst setting, use: Where x is an integer from 1 to 7, inclusive. Returns an integer representing the Day (dd or d) part of the specified date. This the same as datepart(dd, date) Returns an integer representing the Month (mm or m) part of the specified date. This the same as datepart(mm, date) Returns an integer representing the Year (mm or m) part of the specified date. This the same as datepart(yy, date)

publishing dates and to add one week to each publishing date: select title, pubdate, dateadd(ww,1,pubdate) from titles

To get the difference, in months, between the publishing date of a title and the current date i.e. find out how long since the title was published or until it will be published: select title, pubdate, datediff (mm, pubdate, getdate()) from titles If today is 31st December 2003: Select datepart (mm, getDate()) = 12

Day (date) Month

If today is 31st December 2003: Select day (getdate()) = 31 If today is 31st December 2003: Select month (getdate()) = 12 If today is 31st December 2003: Select year (getdate()) = 2003

Year

When working with dates, e.g. inserting date values or comparing date values, different date formats can be used. A date value should be enclosed in single quotes, like a string. When the data type is datetime, SQL will convert the string to a datetime value. Formats accepted are: Alphabetic e.g. 'December 31, 2003' Numeric e.g. '12/31/03'
Page 4 of 10

FBE Computer Science Dept

130999249.doc

Unseparated string e.g. '20031231'

Note that the default date format in SQL Server is to put the month before the date e.g. 12/31/03 this is the US format. This is different to the European date format which puts the date before the month e.g. 31/12/03. The date format depends also on the Regional settings on the server. However, you can specify the date format for SQL to use when converting strings to dates, using the following SQL: Or Be aware of this when working with dates as, for example, you could intend to enter a date of May 3rd, 2003. If you enter it as '3/5/03' it could be interpreted by SQL Server as being March 5th, 2003. It should be entered as '5/3/03'. 5 Views 1.2 Definition A SQL view is a virtual table the contents of the virtual table are defined by a query. A view consists of a set of named columns and rows of data like a table. It can be treated like a table e.g. it can be selected from in a query. However, unlike a table, a view does not exist as a stored set of data values in the database. The rows and columns of data come from the tables referenced in the query that defines the view and are produced dynamically only when the view itself is referenced. In other words, what is stored in the database is the definition of the view the SELECT query that defines it. The result set of that SELECT statement forms the content of the virtual table that is returned by the view when it is referenced e.g. in the FROM clause of a SELECT query. 1.3 Uses of Views Views are usually used for the following: To filter the tables in the defining query the rows and or columns in a table or tables can be filtered. This is often used in cases where only certain data (rows and columns) should be seen and/or updated by a particular user or group of users, or where only certain data is required to carry out some function. To join columns from multiple tables so that they appear like a single table To aggregate information instead of supplying details e.g. to show only the SUM, MIN or MAX of a particular column.

Data in the tables referenced by the defining query can usually be updated by updating the view.
Page 5 of 10

FBE Computer Science Dept

130999249.doc

1.4

CREATE VIEW Statement

A view can be created using the Create View statement. The syntax is as follows: Take, for example, the titles and publishers table in the pubs demo database on SQL Server. It is likely that a listing of titles together with publishers is frequently required. This listing can be obtained by joining the two tables as follows: To create a view based on this query, we use the CREATE VIEW SQL statement. When this statement is executed, it does not return the rows from titles and pubs it creates a view object in the database. This view can now be used as a table e.g. rows can be selected from it: Generally, all the parts of the SELECT statement can be used when creating a view, but the ORDER BY clause cannot be used. If it is necessary to order the results, they can be ordered when selecting from the view e.g. 1.5 DROP VIEW Statement If/when a view is no longer required in the database, it can be dropped using the DROP VIEW statement: Also, if you want to re-create a view, it needs to be dropped first. 1.6 Views in Enterprise Manager To see what views exist in a database, open the Enterprise Manager, navigate to the database and then click the + next to the database name (e.g. pubs) and then click on Views. There are two system views created when a database is created (sysconstraints and syssegments). If any user views have been created in the database, they will also appear here. Modify a View To see the definition for a view, double-click on it. This brings up the View Properties dialog. In this window, you can see the SQL that creates the view, including the Create View statement. To modify the query that defines the view, edit the SQL here. Click the Check Syntax button after making a change if there are any errors in the SQL, they will be reported when the button is clicked. Click Apply to apply the changes to the view after applying, you can switch to the Query Analyzer to check that the view contents are as you expect. Click OK to apply the changes to the view and to exit from the dialog.
Page 6 of 10

FBE Computer Science Dept

130999249.doc

You can also modify a view in the Design View right-click on the view and choose Design View. This opens up the Query Designer see the following section, Create a New View, for more information about using the Query Designer. Create a New View A new view can also be created in the Enterprise Manager, as follows. Right-click on the Views item under the database name in the left pane Click 'New View' This opens the Query Designer In the Query Designer, you can enter the SQL for the query and/or add tables to the graphical display, create joins between them and select columns (similar to building a query in MS Access) To add a table to the query, right-click in the top pane of the window and select 'Add table' On the Tables tab, select one or more tables to add and click Add Existing views can also be added to the query, by clicking on the Views tab When finished adding tables, click the Close button If there are relationships between the tables (as defined by foreign key constraints), they will be shown in the window The Query Designer will automatically write the SQL to join the tables based on the relationships the SQL appears in the SQL pane, in the bottom half of the window To add a column to be selected, check the box next to the desired column This will cause the column to be added to the listing of columns, below the graphical area, and also to the SQL for the query. The query designer window, being used to create the view vwTitlesPubs for which the SQL was provided above, is shown in Figure 1 below.

Page 7 of 10

FBE Computer Science Dept

130999249.doc

Figure 1 creating a new view in Enterprise Manager the query designer window

To execute the query and see the results, click the Run button in the toolbar this is the red exclamation mark icon (!). When the query is run, the results are shown in the bottom panel for the window see Figure 2 below. Use this to check that the query is as you expect it to be. If it is necessary to make changes, do so and run again to check the results.

Page 8 of 10

FBE Computer Science Dept

130999249.doc

Figure 2 creating a view in Enterprise Manager the results are shown in the bottom panel after clicking the Run button in the toolbar

When you are happy with the query, click the Save icon in the toolbar to create the view. You will be prompted to provide a name for the view enter a name and click OK to save. When finished working with the view, close the query designer window. The new view should now appear in the list of views in the database.

Drop a view To drop a view in Enterprise Manager, navigate to the Views list in the database. Click on the view to be dropped, and hit the Delete key or right-click and choose Delete. This will bring up the Drop Objects dialog. To see if there are any objects dependent on the view and what objects it is dependent on, click the Show Dependencies button. Make sure that only the view you want to drop is listed, then click Drop All to drop it. If there are any objects that depend on the view e.g. another view or a stored procedure that references it, the view cannot be dropped until those objects are dropped. SQL Server will warn if this is the case and will not drop the view.

Page 9 of 10

FBE Computer Science Dept

130999249.doc

1.7 Some points to note A view can reference other views so an existing view can be used as part of the defining query for another view The columns selected in a view can be named, in the same way that columns can be named in a select query e.g. 6 Some Miscellaneous Transact-SQL Commands/Functions This section covers various small things in T-SQL that we have not already explicitly covered, but may have used in class. To comment a line when writing SQL, use two dashes (--) To change the current database, type the 'use' statement followed by the name of the database into which you want to change e.g. To signal the end of a batch of SQL statements 'GO'. At this point, the batch will be sent to the server for execution. GO is not a SQL statement (and is not part of the SQL92/99 standards) but is recognized by the Query Analyzer program. The current batch is all statements entered since the last GO or since the start of the block of SQL statements. If you save a set of SQL scripts for creating tables in a database and then inserting data into those tables, a GO can be placed after the table creation statements. This means the tables will be created before the data is inserted. For example: To indicate that a single quote is part of a string and not the delimiter for the string, replace the quote with two single quotes. For example, if inserting the last name "O'Sullivan" into a database field, the apostrophe before the S is a single quote. If the string O'Sullivan is delimited with single quotes for an insert query, an error like the following will be returned: The correct syntax is shown in the second query below: Some others which we will cover in class if time permits: Exists Operator Union Operator Convert Cast Notes prepared by: Terri O'Sullivan, FBE Computer Science Department.

Page 10 of 10

Você também pode gostar