Presentation is loading. Please wait.

Presentation is loading. Please wait.

Session 11 Creating Tables and Using Data Types. RDBMS and Data Management/Session 11/2 of 40 Session Objectives Define the data types and list the categories.

Similar presentations


Presentation on theme: "Session 11 Creating Tables and Using Data Types. RDBMS and Data Management/Session 11/2 of 40 Session Objectives Define the data types and list the categories."— Presentation transcript:

1 Session 11 Creating Tables and Using Data Types

2 RDBMS and Data Management/Session 11/2 of 40 Session Objectives Define the data types and list the categories in SQL Server 2005. Describe how to create, modify and drop tables in a SQL Server database. Describe how to add, modify and drop columns and constraints in a table. Describe how to work with typed and untyped XML. Explain how to create, use, and view XML schemas. Explain how to use XQuery to access XML data.

3 RDBMS and Data Management/Session 11/3 of 40 Data Types A data type is an attribute that specifies the type of data an object can hold and its storage capacity. Data types enforce data integrity. SQL Server 2005 supports three kinds of data types: System-defined data types: These are provided by SQL Server 2005. Alias data types: These are based on the system-supplied data types. User-defined types: These are created using programming languages supported by the.NET Framework.

4 RDBMS and Data Management/Session 11/4 of 40 System-defined Data Types 1-4 CategoryData TypeDescription Exact Numerics int (4)A column of this type occupies 4 bytes of memory space. Is typically used to hold integer values. smallint (2)A column of this type occupies 2 bytes of memory space. Can hold integer data from –32,768 to 32,767. tinyint (1)A column of this type occupies 1 byte of memory space. Can hold integer data from 0 to 255. bigint (8)A column of this type occupies 8 bytes of memory space. Can hold data in the range -2^63 (- 9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) numeric (19)A column of this type has fixed precision and scale. money (8)A column of this type occupies 8 bytes of memory space. Represents monetary data values ranging from (– 2^63/10000) (–922,337,203,685,477.5808) through 2^63–1 (922,337,203,685,477.5807).

5 RDBMS and Data Management/Session 11/5 of 40 System-defined Data Types 2-4 CategoryData TypeDescription Approximate Numerics float (8)A column of this type occupies 8 bytes of memory space. Represents floating point number ranging from –1.79E +308 through 1.79E+308. Real (4)A column of this type occupies 4 bytes of memory space. Represents floating precision number ranging from –3.40E+38 through 3.40E+38. Date and Time Datetime (4)Represents date and time. Stored as two 4-byte integers. Smalldatetime (2)Represents date and time.

6 RDBMS and Data Management/Session 11/6 of 40 System-defined Data Types 3-4 CategoryData TypeDescription Character String Char (8000)Stores character data that is fixed-length and non-Unicode. Varchar (8000)Stores character data that is variable-length and non-Unicode. textStores character data that is variable- length and non-Unicode. Unicode Types ncharStores Unicode character data of fixed-length. nvarcharStores variable-length Unicode character data. ntextStores variable-length Unicode character data.

7 RDBMS and Data Management/Session 11/7 of 40 System-defined Data Types 4-4 CategoryData TypeDescription Other Data Types Timestamp (8)A column of this type occupies 8 bytes of memory space. Can hold automatically generated, unique binary numbers that are generated for a database. Binary (8000)Stores fixed-length binary data with a maximum length of 8000 bytes.. Varbinary (8000)Stores variable-length binary data with a maximum length of 8000 bytes. imageStores variable-length binary data with a maximum length of 2^30–1 (1,073,741,823) bytes. Uniqueidentifier (16)A column of this type occupies 16 bytes of memory space. Also stores a globally unique identifier (GUID).

8 RDBMS and Data Management/Session 11/8 of 40 Alias Data Types 1-2 CREATE TYPE [ schema_name. ] type_name {FROM base_type [ ( precision [, scale ] ) ] [ NULL | NOT NULL ] } [ ; ] Syntax: where, schema_name identifies the name of the schema. type_name identifies the name of the alias type. base_type identifies the name of the system-defined data type based on which the alias data type is being created. precision and scale specify the precision and scale for numeric data. NULL | NOT NULL specifies whether the data type can hold a null value or not. Alias data types are based on the system-supplied data types. They can be created using CREATE TYPE statement

9 RDBMS and Data Management/Session 11/9 of 40 Alias Data Types 2-2 CREATE TYPE usertype FROM varchar(20) NOT NULL Example: Output:

10 RDBMS and Data Management/Session 11/10 of 40 Creating Tables CREATE TABLE [database_name]. [ schema_name ] table_name ( { | } [ ] [,...n ] ) [ ; ] ::= column_name ::= [ type_schema_name. ] type_name ::= [ CONSTRAINT constraint_name ] { { PRIMARY KEY | UNIQUE }] | [ FOREIGN KEY ] REFERENCES [ schema_name. ] referenced_table_name [ ( ref_column ) ] [ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ] [ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ] | CHECK ( logical_expression ) Syntax: CREATE TABLE PhoneGallery ( PhoneID int, Photo varbinary(max) ) GO INSERT INTO PhoneGallery (PhoneID, Photo) GO SELECT TOP 10 ProductPhotoID, ThumbNailPhoto FROM Production.ProductPhoto GO Example :

11 RDBMS and Data Management/Session 11/11 of 40 Column Nullability  The nullability feature of a column determines whether rows in the table can contain a null value for that column.  Nullability of a column can be defined either when creating a table or modifying a table. CREATE TABLE StoreDetails (StoreID int NOT NULL, Name varchar(40) NULL) Example:  NULL keyword indicates that null values are allowed in the column.  NOT NULL keywords indicate that null values are not allowed in columns.

12 RDBMS and Data Management/Session 11/12 of 40 DEFAULT Definition 1-2 A DEFAULT definition can be given for a column to assign it a default value if no value is given at the time of creation. A DEFAULT definition for a column can be created at the time of table creation or added at a later stage to an existing table.

13 RDBMS and Data Management/Session 11/13 of 40 DEFAULT Definition 2-2 CREATE TABLE StoreProduct( ProductID int NOT NULL, Name varchar(40) NOT NULL, Price money NOT NULL DEFAULT (100)) INSERT INTO StoreProduct (ProductID, Name) VALUES (111, ‘Rivets’) DEFAULT definitions cannot be created on columns defined with:  A timestamp data type  An IDENTITY or ROWGUIDCOL property  An existing default definition or default object Example:

14 RDBMS and Data Management/Session 11/14 of 40 IDENTITY Property 1-2 The IDENTITY property of SQL Server is used to create identifier columns that can contain auto-generated sequential values to uniquely identify each row within a table. An identity property has two components: seed value and increment The table shows the various keywords and functions that can be used with identity columns: Property/FunctionDescription IDENTITYCOL keywordRetrieves value of the identifier column OBJECTPROPERTY() functionDetermines if a table has an IDENTITY column COLUMNPROPERTY functionRetrieves the name of the IDENTITY column in a table

15 RDBMS and Data Management/Session 11/15 of 40 IDENTITY Property 2-2 Syntax: CREATE TABLE (column_name data_type [ IDENTITY [(seed_value, increment_value)]] NOT NULL ) where, seed_value is a value from which identity values will start. increment_value is an increment value by which to increase the identity value each time. CREATE TABLE Person.ContactPhone ( Person_ID int IDENTITY(500,1) NOT NULL, MobileNumber bigint NOT NULL ) Example: Here, in this example, 500 is the seed identity value and 1 is the increment.

16 RDBMS and Data Management/Session 11/16 of 40 Globally Unique Identifiers 1-2 Globally unique identifier columns can be created for tables to contain values that are unique across all the computers in a network. Only one identifier column and one globally unique identifier column can be created for each table. To create and work with globally unique identifiers, a combination of ROWGUIDCOL, uniqueidentifier data type and NEWID function are used.

17 RDBMS and Data Management/Session 11/17 of 40 Globally Unique Identifiers 2-2 CREATE TABLE Person.CellularPhone( Person_ID uniqueidentifier DEFAULT NEWID() NOT NULL, PersonName varchar(60) NOT NULL) INSERT INTO Person.CellularPhone(PersonName) VALUES(‘William Smith’) GO SELECT * FROM Person.CellularPhone Example: Output:

18 RDBMS and Data Management/Session 11/18 of 40 Constraints A constraint is a property assigned to a column or set of columns in a table to prevent certain types of inconsistent data values from being entered. SQL Server supports the following types of constraints: PRIMARY KEY UNIQUE FOREIGN KEY CHECK NOT NULL

19 RDBMS and Data Management/Session 11/19 of 40 The PRIMARY KEY constraint is used to create a primary key comprising a single column or combination of columns to uniquely identify each row within a table. Primary Key CREATE TABLE ( Column_name datatype PRIMARY KEY [, column_list] ) CREATE TABLE Person.ContactPhone ( Person_ID int PRIMARY KEY, MobileNumber bigint, ServiceProvider varchar(30), LandlineNumber bigint) CREATE TABLE ( [, column_list] CONSTRAINT constraint_name PRIMARY KEY) Syntax: Example: Alternative Syntax to create a Primary Key constraint:

20 RDBMS and Data Management/Session 11/20 of 40 UNIQUE 1-2 A UNIQUE constraint is used to ensure that only unique values are entered in a column or set of columns. It allows developers to make sure that no duplicate values are entered. Primary keys are implicitly unique. Unique key constraints enforce entity integrity because once the constraints are applied, no two rows in the table can have the same value for the columns. UNIQUE constraints allow null values.

21 RDBMS and Data Management/Session 11/21 of 40 UNIQUE 2-2 CREATE TABLE ([column_list, ] UNIQUE [,column_list]) Syntax: CREATE TABLE Person.ContactPhone (Person_ID int PRIMARY KEY, MobileNumber bigint UNIQUE,ServiceProvider varchar(30),LandlineNumber bigint UNIQUE) Example: Or: CREATE TABLE ([column_list, ] constraint const_name UNIQUE [,column_list])

22 RDBMS and Data Management/Session 11/22 of 40 FOREIGN KEY 1-2 A foreign key in a table is a column that points to a primary key column in another table. Foreign key constraints are used to enforce referential integrity.

23 RDBMS and Data Management/Session 11/23 of 40 FOREIGN KEY 2-2 CREATE TABLE Person.PhoneExpenses (Expense_ID int PRIMARY KEY, MobileNumber bigint FOREIGN KEY REFERENCES Person.ContactPhone (MobileNumber), Amount bigint) Example: CREATE TABLE ([ column_list,] FOREIGN KEY REFERENCES (pk_column_name> [, column_list]) Syntax: Or: CREATE TABLE ([ column_list,] constraint const_name FOREIGN KEY REFERENCES (pk_column_name> [, column_list])

24 RDBMS and Data Management/Session 11/24 of 40 CHECK Constraint A CHECK constraint limits the values that can be placed in a column. Check constraints enforce integrity of data. CREATE TABLE Person.PhoneExpenses ( Expense_ID int PRIMARY KEY, Amount bigint CHECK (Amount >0)) Example: CREATE TABLE Person.PhoneExpenses ( Expense_ID int PRIMARY KEY, Amount bigint CONSTRAINT CK_Amount CHECK (Amount >0))

25 RDBMS and Data Management/Session 11/25 of 40 NOT NULL Constraint A NOT NULL constraint enforces that the column will not accept null values. The NOT NULL constraints are used to enforce domain integrity, similar to the check constraints. Adding Columns to an Existing Table CREATE TABLE ([ column_list,] NOT NULL [, column_list]) Syntax: Or: CREATE TABLE ([ column_list,] constraint const_name NOT NULL [, column_list])

26 RDBMS and Data Management/Session 11/26 of 40 Adding Columns to an Existing Table ALTER TABLE ADD [,,...] ALTER TABLE Person.ContactPhone ADD RentalCharges money Syntax: Example:

27 RDBMS and Data Management/Session 11/27 of 40 Modifying Columns in a Table ALTER TABLE ALTER COLUMN [,...] Syntax: Example: ALTER TABLE Person.ContactPhone ALTER COLUMN ServiceProvider varchar(45)

28 RDBMS and Data Management/Session 11/28 of 40 Dropping Columns from a Table ALTER TABLE DROP COLUMN [,...] ALTER TABLE Person.ContactPhone DROP COLUMN ServiceProvider Syntax: Example:

29 RDBMS and Data Management/Session 11/29 of 40 Adding and Removing Constraints ALTER TABLE ADD CONSTRAINT [ ] Syntax: Example: ALTER TABLE Person.ContactPhone ADD CONSTRAINT CHK_RC CHECK (RentalCharges >0) ALTER TABLE DROP CONSTRAINT Syntax: Example: ALTER TABLE Person.ContactPhone DROP CONSTRAINT CHK_RC

30 RDBMS and Data Management/Session 11/30 of 40 Examples alter table student add constraint pk_code primary key (code) alter table student add constraint uni_code unique (code) alter table student add constraint def_phone default ‘N/A’ for phone alter table mark add constraint fk_code foreign key (code) references student (code) on delete cascade on update set null alter table mark add constraint ck_mark check ( mark in (3, 5, 6) )

31 RDBMS and Data Management/Session 11/31 of 40 Working with XML Advantages of working with native XML databases in SQL Server 2005 are: Easy Data Search and Management: All the XML data is stored locally in one place, thus making it easier to search and manage. Better Performance: Queries from a well-implemented XML database are faster than queries over documents stored in a file system. Also, the database essentially parses each document when storing it. Easy data processing: Large documents can be processed easily.

32 RDBMS and Data Management/Session 11/32 of 40 Creating a Table with xml Column CREATE TABLE ( [ column_list,] xml [, column_list]) CREATE TABLE Person.PhoneBilling (Bill_ID int PRIMARY KEY, MobileNumber bigint UNIQUE, CallDetails xml) INSERT INTO Person.PhoneBilling VALUES (100,9833276605,‘ Local 45 minutes 200 ’) SELECT CallDetails FROM Person.PhoneBilling Syntax: Example: Output:

33 RDBMS and Data Management/Session 11/33 of 40 Typed and Untyped XML There are two ways of storing XML data in xml data type columns and variables: Typed Untyped XML An XML instance which has a schema associated with it is called typed XML instance. Here, data can be validated while it is being stored into the xml column. An untyped XML instance is one which does not have any association with an XML schema. SQL Server does not perform any validation for data entered in the xml column.

34 RDBMS and Data Management/Session 11/34 of 40 XML Schema CREATE XML SCHEMA COLLECTION CricketSchemaCollection AS N’ Example: ’

35 RDBMS and Data Management/Session 11/35 of 40 Using Typed XML CREATE TABLE CricketTeam (TeamID int IDENTITY NOT NULL, TeamInfo xml(CricketSchemaCollection) ) INSERT INTO CricketTeam (TeamInfo) VALUES (‘ ’) Example: DECLARE @team xml(CricketSchemaCollection) SET @team = ‘ ’ SELECT @team Example:

36 RDBMS and Data Management/Session 11/36 of 40 XQuery 1-4 XQuery:  Allows to query and retrieve XML data using a language named XQuery.  Combines syntax that is familiar to developers who work with the relational database, and XPath language, that is used to select individual sections or collections of elements from an XML document.  Can query structured or semi-structured XML data.

37 RDBMS and Data Management/Session 11/37 of 40 XQuery 2-4 USE AdventureWorks SELECT TeamID FROM CricketTeam WHERE TeamInfo.exist(‘(/MatchDetails/Team)’) = 1 USE AdventureWorks SELECT TeamInfo.query(‘/MatchDetails/Team’) AS Info FROM CricketTeam Example: The xml data type methods that can be used with XQuery expressions are: exist(): The exist() method is used to determine if one or more specified nodes are present in the XML document. query(): The query() method can be used to retrieve either the entire contents of an XML document or a selected section of the XML document.

38 RDBMS and Data Management/Session 11/38 of 40 XQuery 3-4 Output:

39 RDBMS and Data Management/Session 11/39 of 40 XQuery 4-4 The value() method can be used to extract scalar values from a datatype. USE AdventureWorks SELECT TeamInfo.value(‘(/MatchDetails/Team/@score)[1]’, ‘varchar(20)’) AS Score FROM CricketTeam where TeamID=1 Example: Output:

40 RDBMS and Data Management/Session 11/40 of 40 Summary A data type is an attribute used to specify the type of data an object can hold and also its size. SQL Server 2005 supports three kinds of data types: system-defined data types, alias data types, and user-defined data types. The nullability feature of a column determines whether rows in the table can contain a null value for that column. SQL Server uses NULL and NOT NULL keywords to deal with nullability. The DEFAULT keyword is used to assign default definitions to columns whose values may not be known, while the IDENTITY property of SQL Server is used to create identifier columns that can contain auto- generated sequential values to uniquely identify each row within a table. A constraint is a rule that can be assigned to a column or set of columns in a table to enforce integrity. The xml data type is used to store XML documents and fragments in an SQL Server database. XQuery is a language used to query XML data stored in native XML databases.


Download ppt "Session 11 Creating Tables and Using Data Types. RDBMS and Data Management/Session 11/2 of 40 Session Objectives Define the data types and list the categories."

Similar presentations


Ads by Google