0% found this document useful (0 votes)
39 views

Handout 6 - Advanced Data Types, DateTime Functions, Views

This document provides a summary of advanced data types, date-time functions, and views in SQL Server. It covers decimal, numeric, text, image, nchar, varchar, ntext, and other data types. It also discusses storing data as ASCII or Unicode, and issues related to supporting multiple languages. Finally, it describes datetime functions like GetDate() and DateAdd() for working with date and time values.

Uploaded by

Roha Cbc
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Handout 6 - Advanced Data Types, DateTime Functions, Views

This document provides a summary of advanced data types, date-time functions, and views in SQL Server. It covers decimal, numeric, text, image, nchar, varchar, ntext, and other data types. It also discusses storing data as ASCII or Unicode, and issues related to supporting multiple languages. Finally, it describes datetime functions like GetDate() and DateAdd() for working with date and time values.

Uploaded by

Roha Cbc
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

CCI – Computer Science Dept 655445337.

doc

Haramaya University
College of Computing and informatics

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 Description Storage size
SQL-92 standard)
Decimal (p,s) decimal Precision and scale values up to 38 1-9 = 5 bytes
Numeric (p,s) digits long i.e. from –(10^38) + 1 to 10-19 = 9 bytes
(10^38) – 1; 20-28 = 13 bytes
p is precision – this is the max total 29-38 = 17 bytes
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.
Text Not a SQL92/99 data Variable length character data, A byte per character
type – specific to maximum length is (2^31) – 1
SQL Server characters; this is useful for storing
large pieces of text in a database field.
Image Not a SQL92/99 data Variable length binary data, maximum As many bytes as are stored
type – specific to length is (2^31) – 1 bytes; in the field
SQL Server
nchar (n) National character Fixed-length Unicode* data where the 2 * n bytes (8000 bytes
maximum length is n characters, n is in maximum)
the range 1 to 4000.
If n is not specified, the default is 1.
Page 1 of 11
CCI – Computer Science Dept 655445337.doc

varchar(n) National character Variable-length Unicode data where the Depends on the number of
varying maximum length is n; n must be in the characters entered (1
range 1 to 4000. character = 2 bytes)
If n is not specified, the default is 1.
ntext Variable length Unicode data, 2 times the number of
maximum length is (2^30) – 1 characters entered
characters.

* 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.

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.
Page 2 of 11
CCI – Computer Science Dept 655445337.doc

3.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 Description Examples


GetDate() Returns the current system date and time, Select getdate()
in the SQL Server internal format This would return the current
date and time e.g.
2003-12-31 11:04:35.680
- the internal format uses yyyy-
mm-dd for the date part and
hh:mm:ss.ms for the time part
(24 hour clock)
DateAdd (datepart, number, date) Adds a specified interval to a date, and To add one year to the current
returns a new datetime value to reflect the date:
addition. Select Dateadd(yy, 1, getdate())
Datepart can be any of the following – If today is 31st December 2003,
and there are abbreviations that can be then this will return 31st
used for each e.g. yy or yyyy for Year: December 2004.
Year (yy, yyyy)
Quarter (qq, q) To show a list of titles and their
Month (mm, m) publishing dates and to add one
Dayofyear (dy, y) week to each publishing date:
Day (dd, d) select title, pubdate,
Week (wk, ww) dateadd(ww,1,pubdate)

Page 3 of 11
CCI – Computer Science Dept 655445337.doc

Hour (hh) from titles


Minute (mi, n)
Second (ss, s)
Millisecond (ms)
DateDiff (datepart, startdate, Returns the difference between two dates. To get the difference, in months,
enddate) The difference can be calculated on any between the publishing date of a
part of a date – year, quarter, month etc title and the current date i.e. find
(as listed for the Date Parts in DateAdd out how long since the title was
above). The datepart parameter specifies published or until it will be
the part on which to calculate the published:
difference e.g. to get the difference in
days, months, weeks or years etc. select title, pubdate, datediff
The startdate value is subtracted from the (mm, pubdate, getdate()) from
enddate value – so if the startdate is later titles
than the enddate, a negative value is
returned.
DatePart (datepart, date) Returns an integer representing the If today is 31st December 2003:
specified datepart of the specified date. Select datepart (mm, getDate())
The datepart can be any of the values = 12
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
select @@datefirst
- 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:
set datefirst x
Where x is an integer from 1 to 7,
inclusive.
Day (date) Returns an integer representing the Day If today is 31st December 2003:
(dd or d) part of the specified date. Select day (getdate())
This the same as datepart(dd, date) = 31
Month Returns an integer representing the Month If today is 31st December 2003:
(mm or m) part of the specified date. Select month (getdate())
This the same as datepart(mm, date) = 12

Year Returns an integer representing the Year If today is 31st December 2003:
(mm or m) part of the specified date. Select year (getdate())
This the same as datepart(yy, date) = 2003

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'
 Unseparated string e.g. '20031231'

Page 4 of 11
CCI – Computer Science Dept 655445337.doc

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:
SET dateformat 'dmy' -- sets the format to be date then month
Select datepart (m, '6/2/04') -- should return 2 as 2 is the month part
Or
SET dateformat 'mdy' -- sets the format to be month then date
Select datepart (m, '6/2/04') -- should return 6 as 6 is now the month part

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
5.1 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.

5.2 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 11
CCI – Computer Science Dept 655445337.doc

5.3 CREATE VIEW Statement

A view can be created using the Create View statement. The syntax is as follows:

CREATE [ownername.]VIEW view_name


AS
Select_statement

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:

SELECT t.title_id, t.title, t.price, t.pub_id, p.pub_name


FROM titles t, publishers p
WHERE t.pub_id = p.pub_id

To create a view based on this query, we use the CREATE VIEW SQL statement.

CREATE VIEW vwTitlesPubs AS


SELECT t.title_id, t.title, t.price, t.pub_id, p.pub_name
FROM titles t, publishers p
WHERE t.pub_id = p.pub_id

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:

SELECT * FROM vwTitlesPubs

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.

SELECT * FROM vwTitlesPubs ORDER BY Title

5.4 DROP VIEW Statement


If/when a view is no longer required in the database, it can be dropped using the DROP
VIEW statement:

DROP VIEW vwTitlesPubs

Also, if you want to re-create a view, it needs to be dropped first.

5.5 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
Page 6 of 11
CCI – Computer Science Dept 655445337.doc

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.

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 11
CCI – Computer Science Dept 655445337.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 11
CCI – Computer Science Dept 655445337.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 11
CCI – Computer Science Dept 655445337.doc

5.6 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.
CREATE VIEW vwTitlesPubs AS
SELECT t.title_id, t.title, t.price, 'PublisherID' = t.pub_id, 'PublisherName' = p.pub_name
FROM titles t, publishers p
WHERE t.pub_id = p.pub_id

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 (--)


-- for example, this is a comment
-- below is a select statement
select * from titles

To change the current database, type the 'use' statement followed by the name of the
database into which you want to change e.g.
-- the next line of SQL will switch into the pubs database
use pubs

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:
Use my_database_name
GO
Create table mytable (
Column1 int not null,
Column 2 int
)
GO
Insert into mytable (Column1, Column2) values (1,2)
GO

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:

Server: Msg 170, Level 15, State 1, Line 1


Line 1: Incorrect syntax near 'Sullivan'.
Server: Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark before the character string ')'.

The correct syntax is shown in the second query below:


Page 10 of 11
CCI – Computer Science Dept 655445337.doc

-- this insert will return an error


Insert into Employees (Name, FathersName) values ('Terri', 'O'Sullivan')
-- this insert will succeed – note the two single quotes in place of the single quote inside the
-- string
Insert into Employees (Name, FathersName) values ('Terri', 'O''Sullivan')

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 11 of 11

You might also like