• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
05 qmds2005 session07
 

05 qmds2005 session07

on

  • 366 views

 

Statistics

Views

Total Views
366
Views on SlideShare
350
Embed Views
16

Actions

Likes
0
Downloads
0
Comments
0

2 Embeds 16

http://niitcourseslides.blogspot.in 15
http://niitcourseslides.blogspot.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Start the session with explaining the objectives to the students. Note Create a new user named Samual, give dbcreator permission to the user and then create the database. Use the following statement to to create the user and provide the dbcreator role: CREATE LOGIN Samual WITH PASSWORD ='niit#1234' EXEC sys.sp_addsrvrolemember @loginame = N'Samual', @rolename = N'dbcreator'
  • Explain the students that System databases are the databases which are present in SQL Server by default. These databases help SQL Server to work properly. Additional Input Unlike previous versions of SQL Server, installing or roll backing a service pack is not a big task now. SQL Server 2005 provides Resources database which holds the definitions of all the server specific stored procedures and views. Therefore, while installing a service pack, you need not to remove all the database from the server any more.
  • Example In addition to the example given in the SG, you can also provide the following example that includes all the parameters. CREATE DATABASE Employee ON ( NAME = Employee_dat, FILENAME = 'C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\Employee_Data.mdf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) LOG ON ( NAME = Employee_log, FILENAME = 'C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\Employee_Log.ldf', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) GO Remember that in the preceding statement, the path provided will be the path where the SQL Server is installed.
  • Table Creation Before a table is created, tell your students that the database has to be created. The tables are created in a database. Tell the students that the database has already been created for them. This will not be covered in class. Normally, databases are created and managed by experienced database administrators. While creating a table, it is a good practice to explicitly mention whether an attribute allows null or not null values. Tell the students that it is a good practice to name the tables and attributes meaningfully, and that they should follow the recommended naming conventions. SQL Server does not allow keywords to be used as column names. If a table already exists with a particular name, you will not be able to create another with the same name. You need to drop the table and re-create it again with the same name. Additional Inputs Identity columns can be created to ensure that SQL Server inserts unique values automatically. There can be only one column declared as an identity column. An identity column cannot be updated. It does not allow null values. It can be of the int, smallint, tinyint, and float data types. This property can be used with the CREATE TABLE and ALTER TABLE Transact-SQL statements. Syntax: IDENTITY [ ( seed , increment ) ] Where: seed: specifies the value that is used for the very first row added into the table increment: specifies the incremental value, which needs to be added with the identity value of the previous row that is added
  • Example CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int NOT NULL, LeaveStartDate datetime NOT NULL, LeaveEndDate datetime NOT NULL, LeaveReason varchar(100), LeaveType char(2)NOT NULL )
  • Explain the students that various type of integrities can be used to remove the redundancy from the data stored in a table. Additional Inputs Domain integrity is implemented using the CHECK constraint. Entity integrity is implemented using the PRIMARY KEY constraint. Referential integrity is implemented using the FOREIGN KEY and PRIMARY KEY constraints. User-defined integrity is implemented in the form of business rules using CHECK constraints or triggers.
  • Additional Inputs Constraints can be added while creating the table. They can also be added later using the ALTER TABLE statement. When a constraint is added in an existing table, by default, it checks the existing data. The system tables which store constraint definitions are syscomments, sysreferences, and sysconstraints. To view all the constraints on a table use sp_helpconstraint followed by the table name.
  • Additional Inputs Constraints can be added while creating the table. They can also be added later using the ALTER TABLE statement. When a constraint is added in an existing table, by default, it checks the existing data. The system tables which store constraint definitions are syscomments, sysreferences, and sysconstraints. To view all the constraints on a table use sp_helpconstraint followed by the table name.
  • Additional Inputs Constraints can be added while creating the table. They can also be added later using the ALTER TABLE statement. When a constraint is added in an existing table, by default, it checks the existing data. The system tables which store constraint definitions are syscomments, sysreferences, and sysconstraints. To view all the constraints on a table use sp_helpconstraint followed by the table name.
  • Foreign Key Stress on the fact that a foreign key constraint can refer to another column of another table or another column of the same table. The easiest way to implement referential integrity is to define a PRIMARY KEY constraint on the parent table and a FOREIGN KEY constraint on the child table. If an index is used to implement the primary key and entity integrity on the parent table, then referential integrity can be implemented using a trigger on the child table. Triggers are dealt with in more detail later in the course. Example: Adding a foreign key in the EmployeeLeave table. CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES HumanResources.Employee(EmployeeID), LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY(EmployeeID, LeaveStartDate), … … …
  • Foreign Key Stress on the fact that a foreign key constraint can refer to another column of another table or another column of the same table. The easiest way to implement referential integrity is to define a PRIMARY KEY constraint on the parent table and a FOREIGN KEY constraint on the child table. If an index is used to implement the primary key and entity integrity on the parent table, then referential integrity can be implemented using a trigger on the child table. Triggers are dealt with in more detail later in the course. Example: Adding a foreign key in the EmployeeLeave table. CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES HumanResources.Employee(EmployeeID), LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY(EmployeeID, LeaveStartDate), … … …
  • Check Constraint A CHECK constraint on a column implements domain integrity on the column. A column level CHECK constraint can refer to values of only that column. However, a table level constraint can refer to values of other columns of the same table. Additional Inputs When a CHECK constraint is applied on a column, it verifies the data every time an insertion or an updation happens. A table level check constraint can reference another column on the same table. It cannot be placed on columns having the IDENTITY property. Example: Adding a check constraint in the EmployeeLeave table. CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES HumanResources.Employee(EmployeeID), LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY(EmployeeID, LeaveStartDate), LeaveEndDate datetime NOT NULL, LeaveReason varchar(100), LeaveType char(2) CONSTRAINT chkLeave CHECK(LeaveType IN('CL','SL','PL')) )
  • Check Constraint A CHECK constraint on a column implements domain integrity on the column. A column level CHECK constraint can refer to values of only that column. However, a table level constraint can refer to values of other columns of the same table. Additional Inputs When a CHECK constraint is applied on a column, it verifies the data every time an insertion or an updation happens. A table level check constraint can reference another column on the same table. It cannot be placed on columns having the IDENTITY property. Example: Adding a check constraint in the EmployeeLeave table. CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES HumanResources.Employee(EmployeeID), LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY(EmployeeID, LeaveStartDate), LeaveEndDate datetime NOT NULL, LeaveReason varchar(100), LeaveType char(2) CONSTRAINT chkLeave CHECK(LeaveType IN('CL','SL','PL')) )
  • Default Constraint Stress the fact that a default constraint is used for easing data entry. Additional Inputs A default constraint only applies to insert statements. A default cannot be placed on columns with IDENTITY properties. Example: Adding a default constraint in the EmployeeLeave table. CREATE TABLE HumanResources.EmployeeLeave ( EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES HumanResources.Employee(EmployeeID), LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY KEY(EmployeeID, LeaveStartDate), LeaveEndDate datetime NOT NULL, LeaveReason varchar(100), LeaveType char(2) CONSTRAINT chkLeave CHECK(LeaveType IN('CL','SL','PL')) CONSTRAINT chkDefLeave DEFAULT 'PL' )
  • Rules and Defaults CHECK constraints can also be implemented using rules. Similarly, default constraints can also be implemented using defaults. If the same check constraints or default constraints apply to columns in more than one table, then a rule or default can be created and bound to the columns. Example: Creating a rule, rulType for the LeaveType column of EmployeeLeave table CREATE RULE rulType AS @LeaveType IN ('CL', 'SL', 'PL')
  • User-defined Data types Explain to the students that a user-defined data type is created for an attribute if the attribute appears in more than one table. Besides, a user-defined data type is used to maintain consistency of the system data type used for an attribute across tables. Tell the students that a user-defined data type needs to be created before creating the table. Before dropping a user-defined data type, ensure that it is not being used in any table. Stress again the need for naming the data types meaningfully. Also, ask them to follow the recommended naming conventions. Additional Inputs User-defined data types created in the model database are automatically included in all databases that are subsequently created. Each user-defined data type when created adds a row to the systypes table. The nullability of the column defined in the table, overrides that of the data type’s. Example: Creating an user-defined data type for descriptive columns CREATE TYPE DSCRP FROM varchar(100) NOT NULL ;
  • Example: Adding a column in the existing table EmployeeLeave ALTER TABLE HumanResources.EmployeeLeave ADD ClaimDetails DSCRP NOT NULL CONSTRAINT chkDefClaim DEFAULT 'No Claim‘
  • Table Deletion Tell the students that once a table is dropped, it cannot be referred to unless recreated. Additional Inputs Before dropping a table, you must remove any references between the table and any other object. Example: Removing the EmployeeLeave table. DROP TABLE HumanResources.EmployeeLeave
  • You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  • You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  • You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  • You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  • You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.

05 qmds2005 session07 05 qmds2005 session07 Presentation Transcript

  • Querying and Managing Data Using SQL Server 2005Objectives In this session, you will learn to: Manage databases Manage tables Ver. 1.0 Session 7 Slide 1 of 33
  • Querying and Managing Data Using SQL Server 2005Identifying the System Databases in SQL Server 2005 SQL Server 2005 contains the following system databases: – master: The master database that records all the server-specific configuration information. – tempdb: The temporary database that holds all temporary tables and stored procedures. – model: The model database that acts as a template or prototype for the new databases. – msdb: The database that handles the task of scheduling, exception handling, etc. – Resource: Read-only database that contains all the system objects included in the SQL Server 2005. Ver. 1.0 Session 7 Slide 2 of 33
  • Querying and Managing Data Using SQL Server 2005Just a minute What is the utility of the model database? Answer: The model database acts as a template or a prototype for the new databases. Ver. 1.0 Session 7 Slide 3 of 33
  • Querying and Managing Data Using SQL Server 2005Creating a User-Defined Database User-defined database: Is stored as a set of files. These files include: • Primary data file • Secondary data file • Transaction log file Syntax: CREATE DATABASE database_name [ ON [ PRIMARY ] [ < filespec >]] [ LOG ON { < filespec > [ ,...n ] } ] < filespec > ::= ( [ NAME = logical_file_name , ] FILENAME = os_file_name [ , SIZE = size ] [ , MAXSIZE = { max_size | UNLIMITED } ] [ , FILEGROWTH = growth_increment ] ) [,...n] Let’s see how… Ver. 1.0 Session 7 Slide 4 of 33
  • Querying and Managing Data Using SQL Server 2005Just a minute Which statement is used to create a database? Answer: The CREATE DATABASE statement Ver. 1.0 Session 7 Slide 5 of 33
  • Querying and Managing Data Using SQL Server 2005Creating a Table Table: Is created to store data Is created by using the CREATE TABLE statement Syntax: CREATE TABLE [ database_name . [ schema_name ] .] table_name ( { <column_definition> | <computed_column_definition> } [ <table_constraint> ] [ ,...n ] ) [ ON { partition_scheme_name ( partition_column_name ) | filegroup | "default" } ] [ { TEXTIMAGE_ON { filegroup | "default" } ] [ ; ] Ver. 1.0 Session 7 Slide 6 of 33
  • Querying and Managing Data Using SQL Server 2005Creating a Table (Contd.) Example: Create an EmployeeLeave table in the HumanResources schema with the following details: Columns Data Type Checks EmployeeID int NOT NULL LeaveStartDate date NOT NULL LeaveEndDate date NOT NULL LeaveReason varchar(100) NOT NULL LeaveType char(2) NOT NULL Let’s see how… Ver. 1.0 Session 7 Slide 7 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity Avoids data redundancy Ensures that the data in a database is accurate, consistent, and reliable Is broadly classified into the following categories: Entity integrity: Ensures that each row can be uniquely identified by an attribute called the primary key Domain integrity: Ensures that only a valid range of values is allowed to be stored in a column Referential integrity: Ensures that the values of the foreign key match the value of the corresponding primary key User-defined integrity: Refers to a set of rules specified by a user, which do not belong to the entity, domain, and referential integrity categories Ver. 1.0 Session 7 Slide 8 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) You can maintain data integrity by: Applying constraints Applying rules Using user-defined types Ver. 1.0 Session 7 Slide 9 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) Constraints can be applied: By using CREATE TABLE statement By using ALTER TABLE statement Syntax: CREATE TABLE table_name ( column_name CONSTRAINT constraint_name constraint_type [,CONSTRAINT constraint_name constraint_type] ) Ver. 1.0 Session 7 Slide 10 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) Constraints are of the following types: Primary key constraint Unique constraint Foreign key constraint Check constraint Default constraint Ver. 1.0 Session 7 Slide 11 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) Primary key constraint: Is defined on a column or a set of columns whose values uniquely identify all the rows in a table Does not allow NULL values in the column Ensures entity integrity Syntax: CREATE TABLE table_name ( col_name [CONSTRAINT constraint_name PRIMARY KEY [CLUSTERED|NONCLUSTERED] col_name [, col_name [, col_name [, …]]] ) Ver. 1.0 Session 7 Slide 12 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) Unique constraint: Is defined to enforce uniqueness in non-primary key columns Allows one NULL value in the column Syntax: CREATE TABLE table_name ( col_name [CONSTRAINT constraint_name UNIQUE [CLUSTERED | NONCLUSTERED] (col_name [, col_name [, col_name [, …]]]) col_name [, col_name [, col_name [, …]]] ) Ver. 1.0 Session 7 Slide 13 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) Foreign key constraint: Is defined to remove the inconsistency in two tables when the data in one table depends on the data in another table Associates one or more columns (the foreign key) of a table with an identical set of columns (a primary key column) in another table Ver. 1.0 Session 7 Slide 14 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) Syntax: CREATE TABLE table_name ( col_name [CONSTRAINT constraint_name FOREIGN KEY (col_name [, col_name [, …]]) REFERENCES table_name (column_name [, column_name [, …]])] (col_name [, col_name [, col_name [, …]]]) col_name [, col_name [, col_name [, …]]] ) Let’s see how… Ver. 1.0 Session 7 Slide 15 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) Check constraint: Is defined to enforce domain integrity by restricting the values to be inserted in a column Can be defined on multiple columns Is specified by using the following keywords: IN LIKE BETWEEN Ver. 1.0 Session 7 Slide 16 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) Syntax: CREATE TABLE table_name ( col_name [CONSTRAINT constraint_name] CHECK (expression) (col_name [, col_name [, …]]) . ) Let’s see how… Ver. 1.0 Session 7 Slide 17 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) Default constraint: – Is defined to assign a constant value to a column – Syntax: CREATE TABLE table_name ( col_name [CONSTRAINT constraint_name] DEFAULT (constant_expression | NULL) (col_name [, col_name [, …]]) . ) Let’s see how… Ver. 1.0 Session 7 Slide 18 of 33
  • Querying and Managing Data Using SQL Server 2005Just a minute Which keyword is used to specify a check constraint? Answer: A check constraint can be specified by using the LIKE, IN, and BETWEEN keywords. Ver. 1.0 Session 7 Slide 19 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) Rules: Help in enforcing domain integrity for columns or user-defined data types Can be specified to the column or the user-defined data type before an INSERT or UPDATE statement is issued Are used to implement business-related restrictions or limitations Can be created by using the CREATE RULE statement Syntax: CREATE RULE rule_name AS conditional_expression Can be bound by using the sp_bindrule stored procedure Let’s see how… Ver. 1.0 Session 7 Slide 20 of 33
  • Querying and Managing Data Using SQL Server 2005Implementing Data Integrity (Contd.) User-defined data types: Are custom data types defined by the users with a custom name Can be created by using the CREATE TYPE statement Syntax: CREATE TYPE [ schema_name. ] type_name { FROM base_type [ ( precision [ , scale ] ) ] [ NULL | NOT NULL ] } [ ; ] Let’s see how… Ver. 1.0 Session 7 Slide 21 of 33
  • Querying and Managing Data Using SQL Server 2005Just a minute You want to create a rule, rule1, which allows the user to enter any of the four values: Tea, Coffee, Soup, or Miranda in a column. Which command should you execute? Answer: CREATE RULE rule1 AS @TypeRule IN (Tea, Coffee, Soup, Miranda) Ver. 1.0 Session 7 Slide 22 of 33
  • Querying and Managing Data Using SQL Server 2005Creating a Partitioned Table Flash presentation: Partitioning Tables Partitioned table: Is created when the table contains voluminous data Is created to separate data into multiple physical locations based on a range of values for a specific column Helps in improving query performance Can be created by: Creating a partition function Creating a partition scheme Creating a table by using the partition scheme Ver. 1.0 Session 7 Slide 23 of 33
  • Querying and Managing Data Using SQL Server 2005Modifying a Table Modify a table: When there is a requirement to add or remove columns and constraints Using the ALTER TABLE statement Syntax: ALTER TABLE [ database_name . [ schema_name ] . | schema_name . ] table_name { ALTER COLUMN column_name { [ NULL | NOT NULL ] } | [ WITH { CHECK | NOCHECK } ] ADD COLUMN <column_definition> { ADD CONSTRAINT constraint_name constraint_type Let’s see how… Ver. 1.0 Session 7 Slide 24 of 33
  • Querying and Managing Data Using SQL Server 2005Just a minute You are managing a large table. You want to improve the performance of the table and want the table to be more manageable. Which strategy can you use? Answer: Partition the table Ver. 1.0 Session 7 Slide 25 of 33
  • Querying and Managing Data Using SQL Server 2005Dropping a Table Drop a table: When a table is not required Using the DROP TABLE statement Syntax: DROP TABLE [ database_name . [ schema_name ] . ] table_name Let’s see how… Ver. 1.0 Session 7 Slide 26 of 33
  • Querying and Managing Data Using SQL Server 2005Demo: Managing Tables Problem Statement: The management of AdventureWorks, Inc. has decided to provide travel and medical reimbursements to the employees. They want to store the details of these reimbursements in the database. For this, you need to create a database table, EmployeeReimbursements. The details of the tables are shown in the following table. Columns Data Type and Size Constraints RimID int Primary key EmployeeID int Foreign Key references the EmployeeID of the Employee Table, NOT NULL Amount money Amount>0 RimType varchar(20) RimType should be Medical, Cash, or Local Pending_with varchar(30) NOT NULL How will you create the table? Ver. 1.0 Session 7 Slide 27 of 33
  • Querying and Managing Data Using SQL Server 2005Demo: Managing Tables (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Write the query to create a table. 2. Execute the statement to verify the result. Ver. 1.0 Session 7 Slide 28 of 33
  • Querying and Managing Data Using SQL Server 2005Summary In this session, you learned that: A database is a repository of information that contains data in an organized way. The master database records all the server-specific configuration information, including authorized users, databases, system configuration settings, and remote servers. The tempdb database is a temporary database that holds all temporary tables and stored procedures. The model database acts as a template or a prototype for the new databases. The msdb database supports the SQL Server Agent. The SQL Server Agent includes features that schedule periodic activities of the SQL Server. The Resource database is a read-only database that contains all the system objects that are included with SQL Server 2005. Ver. 1.0 Session 7 Slide 29 of 33
  • Querying and Managing Data Using SQL Server 2005Summary (Contd.) The user-defined databases are created by the users to store data for client-server applications. A database consists of the following types of files: • Primary data file • Secondary data file • Transaction log file – A database must consist of a primary data file and one transaction log file. – The CREATE DATABASE statement is used to create a database, which also includes determining the name of the database, the size of the database, and the files used to store data in the database. – Tables are used to store data. Ver. 1.0 Session 7 Slide 30 of 33
  • Querying and Managing Data Using SQL Server 2005Summary (Contd.) Tables are used to store data. The CREATE TABLE statement is used to create a table. Data integrity is enforced to keep the data in a database accurate, consistent, and reliable. It is broadly classified into the following categories: • Entity integrity: Ensures that each row can be uniquely identified by an attribute called the primary key. • Domain integrity: Ensures that only a valid range of values is allowed to be stored in a column. • Referential integrity: Ensures that the values of the foreign key match the value of the corresponding primary key. • User-defined integrity: Refers to a set of rules specified by a user, which do not belong to the entity, domain, and referential integrity categories. Ver. 1.0 Session 7 Slide 31 of 33
  • Querying and Managing Data Using SQL Server 2005Summary (Contd.) Constraints define rules that must be followed to maintain consistency and correctness of data. A primary key constraint is defined on a column or a set of columns whose values uniquely identify rows in a table. The unique constraint is used to enforce uniqueness on non- primary key columns. A foreign key constraint associates one or more columns of a table (the foreign key) with an identical set of columns on which a primary key constraint has been defined (a primary key column in another table). A check constraint enforces domain integrity by restricting the values to be inserted in a column. The IN, LIKE, and BETWEEN keywords are used to define the check constraint. Ver. 1.0 Session 7 Slide 32 of 33
  • Querying and Managing Data Using SQL Server 2005Summary (Contd.) A default constraint can be used to assign a constant value to a column, and the user need not insert values for such a column. A rule provides a mechanism for enforcing domain integrity for columns or user-defined data types. User-defined data types are custom data types defined by the users with a custom name. A partitioned table is created to manage the data and improve the query performance. The ALTER TABLE statement is used to modify a table. The DROP TABLE statement is used to delete a table. Ver. 1.0 Session 7 Slide 33 of 33