+ All Categories
Home > Documents > Reference Site: functionx/sqlserver

Reference Site: functionx/sqlserver

Date post: 31-Dec-2015
Category:
Upload: avongara-kuron
View: 37 times
Download: 0 times
Share this document with a friend
Description:
TRAINING SESSIONS. SQL Server Basics. Reference Site: http://www.functionx.com/sqlserver/. Design By.:.Net Prepared By:Dilip Namdeo Dated:23-Dec-09. INDEX. Databases CREATE DATABASE DROP DATABASE Tables Views Stored Procedures Functions Triggers Cursors Transact-SQL : Columns - PowerPoint PPT Presentation
30
TRAINING SESSIONS SQL Server Basics gn By.: .Net ared By: Dilip Namdeo d: 23-Dec-09 Reference Site: http://www.functionx.com/sqlserver /
Transcript
Page 1: Reference Site:  functionx/sqlserver

TRAINING SESSIONSTRAINING SESSIONS

SQL Server Basics

Design By.: .NetPrepared By: Dilip NamdeoDated: 23-Dec-09

Reference Site: http://www.functionx.com/sqlserver/

Page 2: Reference Site:  functionx/sqlserver

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

Page 3: Reference Site:  functionx/sqlserver
Page 4: Reference Site:  functionx/sqlserver

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

Page 5: Reference Site:  functionx/sqlserver

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

Page 6: Reference Site:  functionx/sqlserver

Then specify the other properties of the new database:

Page 7: Reference Site:  functionx/sqlserver

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

Page 8: Reference Site:  functionx/sqlserver

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:

Page 9: Reference Site:  functionx/sqlserver

Overview of ViewsWhen 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.

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

Page 10: Reference Site:  functionx/sqlserver

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:

Page 11: Reference Site:  functionx/sqlserver
Page 12: Reference Site:  functionx/sqlserver

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

Page 13: Reference Site:  functionx/sqlserver

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

Page 14: Reference Site:  functionx/sqlserver

DefinitionA 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 ProceduresWhy 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.

Page 15: Reference Site:  functionx/sqlserver

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 ProcedureALTER PROCEDURE ProcedureName

AS

Body of Procedure

Deleting a ProcedureDROP PROCEDURE ProcedureName

Page 16: Reference Site:  functionx/sqlserver

Here is an example of executing the procedure:

Page 17: Reference Site:  functionx/sqlserver

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.

Page 18: Reference Site:  functionx/sqlserver

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

Page 19: Reference Site:  functionx/sqlserver

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 exampleCREATE FUNCTION GetFullName()

RETURNS varchar(100)

AS

BEGIN

RETURN 'Doe, John'

END

Page 20: Reference Site:  functionx/sqlserver

Introduction to TriggersWhen 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

Page 21: Reference Site:  functionx/sqlserver

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.

Page 22: Reference Site:  functionx/sqlserver

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.

Page 23: Reference Site:  functionx/sqlserver

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:DECLARE @id INT --Declaring the Variable @id DECLARE @getID CURSOR -- Declaring the Cursor SET @getID = CURSOR --Assigning the cursor FOR SELECT intID FROM tbl_student --Query related to Cursor OPEN @getID -- Opening the Created cursor FETCH NEXT FROM @getID --Retrieving the record one by one INTO @ID --Assigning the value in declared Variable WHILE @@FETCH_STATUS = 0 BEGIN PRINT @ID FETCH NEXT FROM @getID INTO @ID END CLOSE @getID -- Closing the Cursor DEALLOCATE @getID -- Deallocating the Cursor Memory

Page 24: Reference Site:  functionx/sqlserver

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

Page 25: Reference Site:  functionx/sqlserver

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

Page 26: Reference Site:  functionx/sqlserver

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

Page 27: Reference Site:  functionx/sqlserver

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

Page 28: Reference Site:  functionx/sqlserver

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

Page 29: Reference Site:  functionx/sqlserver

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

Page 30: Reference Site:  functionx/sqlserver

Cheers!

TRAINING SESSIONSTRAINING SESSIONS

Design By.: .NetPrepared By: Dilip NamdeoDated: 23-Dec-09


Recommended