TRAINING SESSIONS SQL Server Basics Design By.:.Net Prepared By:Dilip Namdeo Dated:23-Dec-09 Reference Site:

Slides:



Advertisements
Similar presentations
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Advertisements

Guide to Oracle10G1 Introduction To Forms Builder Chapter 5.
Introduction to Structured Query Language (SQL)
A Guide to Oracle9i1 Introduction To Forms Builder Chapter 5.
A Guide to SQL, Seventh Edition. Objectives Understand the concepts and terminology associated with relational databases Create and run SQL commands in.
SUNY Morrisville-Norwich Campus-Week 12 CITA 130 Advanced Computer Applications II Spring 2005 Prof. Tom Smith.
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
Concepts of Database Management Sixth Edition
30-Jun-15 SQL A Brief Introduction. SQL SQL is Structured Query Language Some people pronounce SQL as “sequel” Other people insist that only “ess-cue-ell”
Introduction to Structured Query Language (SQL)
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
Structured Query Language SQL: An Introduction. SQL (Pronounced S.Q.L) The standard user and application program interface to a relational database is.
8 Copyright © 2004, Oracle. All rights reserved. Creating LOVs and Editors.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
 SQL stands for Structured Query Language.  SQL lets you access and manipulate databases.  SQL is an ANSI (American National Standards Institute) standard.
Chapter 4 The Relational Model 3: Advanced Topics Concepts of Database Management Seventh Edition.
Dinamic SQL & Cursor. Why Dinamic SQL ? Sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can.
1 Working with MS SQL Server Textbook Chapter 14.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Working with MSSQL Server Code:G0-C# Version: 1.0 Author: Pham Trung Hai CTD.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Objectives Database triggers and syntax
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Visual Programing SQL Overview Section 1.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Session 1 Module 1: Introduction to Data Integrity
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
Distribution of Marks For Second Semester Internal Sessional Evaluation External Evaluation Assignment /Project QuizzesClass Attendance Mid-Term Test Total.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
Ch 5. Introducing More Database Objects. Database Objects Table (ch2) View (ch3) Stored Procedure Trigger Function User-defined types.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Ch 3. Working with Tables and Views. Data type Specify type of data to be entered into a column (text, number, datetime, etc) Unicode (National) Datatypes.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
SQL Triggers, Functions & Stored Procedures Programming Operations.
In this session, you will learn to: Create and manage views Implement a full-text search Implement batches Objectives.
Lec-7. The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE.
1 Section 1 - Introduction to SQL u SQL is an abbreviation for Structured Query Language. u It is generally pronounced “Sequel” u SQL is a unified language.
LEC-8 SQL. Indexes The CREATE INDEX statement is used to create indexes in tables. Indexes allow the database application to find data fast; without reading.
Fundamentals of DBMS Notes-1.
Trigger used in PosgreSQL
Web Systems & Technologies
COMP 430 Intro. to Database Systems
Chapter 5 Introduction to SQL.
Creating LOVs and Editors
Data Definition and Data Types
ISC440: Web Programming 2 Server-side Scripting PHP 3
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Introduction To Structured Query Language (SQL)
Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall
Database systems Lecture 3 – SQL + CRUD
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Introduction To Structured Query Language (SQL)
Chapter 8 Advanced SQL.
Presentation transcript:

TRAINING SESSIONS SQL Server Basics Design By.:.Net Prepared By:Dilip Namdeo Dated:23-Dec-09 Reference Site:

 Databases  CREATE DATABASE  DROP DATABASE  Tables  Views  Stored Procedures  Functions  Triggers  Cursors  Transact-SQL :  Columns  Records Operations  Naming Convention

To visually create a database, open Microsoft SQL Server Management Studio. In the Object Explorer, expand the server name followed by the Databases node. Right-click Databases and click New Database...

In the Name text box, type the desired name of the new database. Here is an example:

Then specify the other properties of the new database:

To create a table, you can follow this formula: CREATE TABLE Country( Column1, Column2, Column3); Each column is created as: ColumnName DataType Options Here is an example: CREATE TABLE Customers ( FullName nvarchar(50), Address NVARCHAR(120), City NvarChar(40), State NVarChar(50), PostalCode nvarchar(20), HomePhone nvarchar(20), OrganDonor BIT); GO

You can then modify/customize this code. To visually create a table, in the Object Explorer, expand the database and expand its Tables node. Right-click the Tables node and click New Table... Enter a name for each column and select its data type:

 Overview of Views When studying data analysis, a query is a technique of isolating a series of columns and/or records of a table. This is usually done for the purpose of data analysis. This can also be done to create a new list of items for any particular reason. Most of the time, a query is created temporarily, such as during data analysis while using a table, a form, or a web page. After using such a temporary list, it is then dismissed. Many database applications, including Microsoft SQL Server, allow you to create a query and be able to save it for later use, or even to use it as if it were its own table. This is the idea behind a view.  Definition A view is a list of columns or a series of records retrieved from one or more existing tables, or as a combination of one or more views and one or more tables. Based on this, before creating a view, you must first decide where its columns and records would come from. Obviously the easiest view is one whose columns and records come from one table.

To create a view, you can use the Object Explorer, a query window, the Command Prompt, or Windows PowerShell. Before starting the view, you would have to specify the table(s) that would be involved. To create a view from the Object Explorer, you can expand the database, right-click Views and click New View... This would open the Add Table dialog box:

 To programmatically create a view, you use the following SQL syntax: CREATE VIEW ViewName AS SELECT Statement CREATE VIEW dbo.ListOfMen AS SELECT dbo.Genders.Gender, dbo.Persons.FirstName, dbo.Persons.LastName FROM dbo.Genders INNER JOIN dbo.Persons ON dbo.Genders.GenderID = dbo.Persons.GenderID WHERE (dbo.Genders.Gender = N'Male'); GO

 Open an empty query window associated with the database that contains the view. In the query window, write a SELECT statement using the same formulas and rules we saw for tables. Here is an example:  From the Object Explorer, expand the database and its Views node. Right-click the name of the view and click Open View

 Definition A stored procedure is an already written SQL statement that is saved in the database. A stored procedure is a mechanism to simplify the database development process by grouping Transact-SQL statements into manageable blocks.  Benefits of Stored Procedures Why should you use stored procedures? Let's take a look at the key benefits of this technology:  Precompiled execution: SQL Server compiles each stored procedure once and then reutilizes the execution plan. This results in tremendous performance boosts when stored procedures are called repeatedly.  Reduced client/server traffic: If network bandwidth is a concern in your environment, you'll be happy to learn that stored procedures can reduce long SQL queries to a single line that is transmitted over the wire.

 Efficient reuse of code and programming abstraction: Stored procedures can be used by multiple users and client programs. If you utilize them in a planned manner, you'll find the development cycle takes less time.  Enhanced security controls: You can grant users permission to execute a stored procedure independently of underlying table permissions.  Based on this, the simplest syntax of creating a procedure is: CREATE PROCEDURE ProcedureName AS Body of the Procedure  Modifying a Procedure ALTER PROCEDURE ProcedureName AS Body of Procedure  Deleting a Procedure DROP PROCEDURE ProcedureName

 Here is an example of executing the procedure:

 Stored Procedures vs. User Defined Functions in Microsoft SQL Server  SQL Server user-defined functions and stored procedures offer similar functionality. Both allow you to create bundles of SQL statements that are stored on the server for future use. At first glance, functions and stored procedures seem identical. However, there are several subtle, yet important differences between the two: 1) Stored procedures are called independently, using the EXEC command, while functions are called from within another SQL statement. 2) Functions must always return a value (either a scalar value or a table). Stored procedures may return a scalar value, a table value or nothing at all.

 In Transact-SQL, the primary formula of creating a function is: CREATE FUNCTION FunctionName() For a function to be useful, it must produce a result. This is also said that the function returns a result or a value. When creating a function, you must specify the type of value that the function would return. To provide this information, after the name of the function, type the RETURNS keyword followed by a definition for a data type. Here is a simple example: CREATE FUNCTION Addition() RETURNS Decimal(6,3) After specifying the type of value that the function would return, you can create a body for the function. The body of a function starts with the BEGIN and ends with the END keywords. Here is an example: CREATE FUNCTION Addition() RETURNS Decimal(6,3) BEGIN END

Optionally, you can type the AS keyword before the BEGIN keyword: CREATE FUNCTION Addition() RETURNS Decimal(6,3) AS BEGIN END Between the BEGIN and END keywords, which is the section that represents the body of the function, you can define the assignment the function must perform. After performing this assignment, just before the END keyword, you must specify the value that the function returns. This is done by typing the RETURN keyword followed by an expression. A sample formula is: CREATE FUNCTION Addition() RETURNS Decimal(6,3) AS BEGIN RETURN Expression END  Here is an example CREATE FUNCTION GetFullName() RETURNS varchar(100) AS BEGIN RETURN 'Doe, John' END

 Introduction to Triggers When an action has been performed on a table, such as adding a new record, changing (editing/updating) an existing record, or deleting a (or some) records, the table produces a notification. We say that the table fires an event. You can use this occurring event to take some action. A trigger is an action that is performed behind-the-scenes when an event occurs on a table.  Creating a Trigger: CREATE TRIGGER RecordInsertion ON Rooms AFTER INSERT AS BEGIN INSERT INTO DatabaseOperations VALUES(N'Table', N'Rooms', SUSER_SNAME(), N'Created a new record', GETDATE()) END GO

 After Updating: Instead of record insertion time, a DML trigger can act when a record has been updated on a table. To support this operation, you can use the following formula: CREATE TRIGGER TriggerName ON TableName AFTER/FOR UPDATE AS TriggerCode The new keyword in this formula is UPDATE. This indicates that the DML trigger will act when the record has been updated. Everything else is as described for the INSERT operator. Remember to use either AFTER UPDATE or FOR UPDATE.

 After Deleting:  When a record has been removed from a table, you can apply a DML trigger in response. To make it possible, you can use the following formula: CREATE TRIGGER TriggerName ON TableName AFTER/FOR DELETE AS TriggerCode This time, the formula uses the DELETE operator in an AFTER DELETE or a FOR DELETE expression. This is used for record removal. The other factors follow the same description we saw for the INSERT operator. When a DELETE trigger has acted on a table, the database engine creates a special temporary table named deleted. This table holds a copy of the records that were deleted. Eventually, if necessary, you can access this table to find out about those records.

 Definition: Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time.  Create a simple CURSOR in SQL server: INT --Declaring the CURSOR -- Declaring the Cursor = CURSOR --Assigning the cursor FOR SELECT intID FROM tbl_student --Query related to Cursor -- Opening the Created cursor FETCH NEXT --Retrieving the record one by one --Assigning the value in declared Variable WHILE = 0 BEGIN FETCH NEXT END -- Closing the Cursor -- Deallocating the Cursor Memory

 Adding a Column to a Table: To add a new column to a table, follow this formula: ALTER TABLE TableName ADD ColumnName Properties Here is an example: ALTER TABLE StaffMembers ADD Address varchar(100) NULL GO  Identity Column: An identity column is one whose value is automatically created by the database engine when a new record is added. This makes sure that each record has a unique value for that field. Here is an example: CREATE TABLE StoreItems( I temID int IDENTITY(1, 1) NOT NULL, Category nvarchar(50), ItemName nvarchar(100) NOT NULL, Size nvarchar(20), UnitPrice money); GO

 Deleting a Column: To delete a column using code, first open or access an empty query window, and use the following formula: ALTER TABLE TableName DROP COLUMN ColumnName On the right side of the ALTER TABLE expression, type the name of the table. On the right side of the DROP COLUMN expression, enter the name of the undesired column. Here is an example: ALTER TABLE StaffMembers DROP COLUMN CurrentResidence; GO  Renaming a Column: Execute sp_rename using the following formula: sp_rename 'TableName.ColumnName', 'NewColumnName', 'COLUMN‘ The sp_rename factor and the 'COLUMN' string are required. The TableName factor is the name of the table that the column belongs to. The ColumnName is the current name of the column. The NewColumnName is the desired name you want to give to the column. Here is an example: sp_rename 'StaffMembers.FullName', 'EmployeeName', 'COLUMN' GO

 The Default Value of a Column: To specify the default value in a SQL statement, when creating the column, before the semi-colon or the closing parenthesis of the last column, assign the desired value to the DEFAULT keyword Here are examples: CREATE TABLE Employees ( FullName NVARCHAR(50), Address NVARCHAR(80), City NVARCHAR(40), State NVARCHAR(40) DEFAULT N'NSW', PostalCode NVARCHAR(4) DEFAULT N'2000', Country NVARCHAR(20) DEFAULT N'Australia' ); GO The default value can also come from a function. CREATE TABLE Employees ( EmployeeName nvarchar(50), DateHired date default GETDATE(), Address nvarchar(50), City nvarchar(40), State nchar(2) DEFAULT 'VA‘, ); GO

 Null Values on a Column: To visually create a null field, display the table in Design View: To specify the nullity of a column using SQL, on the right side of the column creation, type NULL. To specify that the values of the column are required, on the right side, type NOT NULL. If you don't specify NULL or NOT NULL, the column will be created as NULL. Here are examples: CREATE TABLE Persons ( FirstName varchar(20) NULL, LastName varchar(20) NOT NULL, Gender smallint ); GO

 Unique Values on a Column: To specify that a column will require unique values, when creating it in SQL, use the UNIQUE keyword. Here is an example: CREATE TABLE Students ( StudentNumber int UNIQUE, FirstName nvarchar(50), LastName nvarchar(50) NOT NULL ); GO When a column has been marked as unique, during data entry, the user must provide a unique value for each new record created. If an existing value is assigned to the column, this would produce an error

 For Table:  tbl_TableName  For View:  vw_ViewName  For StoredProcedure:  usp_USPName  For Function:  udf_UDFName  Commenting: Commenting should be used for SQL statements specially inside the View, USP and UDF. /* Put your comment here */

Cheers! TRAINING SESSIONS Design By.:.Net Prepared By:Dilip Namdeo Dated:23-Dec-09