You are on page 1of 240

Creating an Administrator Account

To actually install Microsoft SQL Server 2008, you must use a user account that has the ability to install it. If you are using Microsoft Windows XP or Vista, you should use the Administrator account or create a new account that has administrative rights. The account you will use must also use/have a password. In Microsoft Windows XP Professional or Vista, to use the Administrator account, assign a password. Alternatively, after logging in as Administrator, create an account that has administrative rights.

Practical Learning: Creating an Account in MS Wnd XP or Vista


1. Start Control Panel and click User Accounts:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

2. Click Create New User:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

3. Type the name for the new account as pkatts:

4. Click Next. Make sure the Computer Administrator radio button is selected

5. Click Create Account 6. To assign a password to an account, in the User Account, click the pkatts account ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

7. Click Create A Password

8. In the Type A New Password text box, type Password1 and press Tab

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

9. Type Password1 to confirm and type anything in the last text box:

10. Click Create Password 11. In the same way, create another account named gmonay that has administrative rights with the password Password1

Practical Learning: Creating an Account in a Server


1. Log in to Microsoft Windows Server 2003 or 3008 with an account that can create an administrative account 2. To create an account in Microsoft Windows Server 2003 or 2008, on the taskbar, you can click Start -> Administrative Tools -> Active Directory Users and Computers

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

3. In the left frame, right-click Users -> New User

4. Set the First Name as Patricia, the Initials as G, the Last Name as Katts, and the User Logon Name as pkatts (the domain name will be different from yours)

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

5. Click Next 6. Type the Password as Password1 7. Type the Confirm Password as Password1 and accept the options in the check boxes

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

8. Click Next (in the summary, the domain name will be different from yours)

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

9. Accept the options in the last page of the wizard and click Finish 10. In the same way, create another account with the following information: First Name: Gertrude LastName: Monay User Logon Name: gmonay Password: Password1

Security Principals
A security principal is a person or an object that needs access to a database. The security principal can be considered as one entity or as a group of entities:

This means that a security principal can be considered as a lone entity or as part of a group. For example, a person who accesses a database can be considered an entity. A group of people who exercise the same function and have been give the same function(s) on a database is considered a collection. To create a group in Microsoft Windows Server 2003 or 2008, open the Active Directory Users and Computers. Right-click the Users node -> New -> Group:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

In the New Object - Group dialog box, give a name to the new group. Make the necessary selections in the Group Scope and the Group Type:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

When you have finished, click OK. After creating a group, you can use it. To use a group, you can add one or more existing users to it. To do this, locate the group and double-click it or right-click the group and click Properties:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Add the necessary information. To control the type of access that a security principal can exercise on a machine or a database, it works or acts on a level. There are three levels: Windows, server, and database:

Based on the functionality of a security principal, it can be considered as belonging to a collection. ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

To help the operating system identify them, each security principal uses a unique number called a security identifier (SID).

Practical Learning: Adding an Account to a Group


1. In the left frame, click Users if necessary. In the right-click frame, double-click Domain Admins 2. In the Domain Admins Properties, click the Members tab (the domain name will be different from yours)

3. Click Add... 4. In the Enter the Object Names to Select text box of the Select Users, Contacts, or Computers dialog box, type pkatts

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

5. Click Check Names (in the result, the domain name will be different from yours)

6. Click OK 7. Click OK

Roles and Logins


A role is an action or a set of actions that are granted to a security principal. For example a person A can be allowed to create and use a database. The ability to perform such an action is referred to as a role. Another person B can be allowed only to use an existing database without being able to create a new one. This is another type of role. In order to access something (such as a computer or a database), the object must be authenticated. Such an object can use a username and a password and use the group it belongs to. For this reason, the ability to be authenticated in order to access the database or resource is called a login. ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

We will see how to create a login in Lesson 3.

Getting Microsoft SQL Server


To make it possible for you and other students to study databases and SQL, Microsoft made available a trial version of Microsoft SQL Server 2008. This full version is available from the Microsoft web site. To get the trial edition of Microsoft SQL Server 2008, go to the Microsoft web site, do a search on "trial software", and follow the links to locate the trial edition of Microsoft SQL Server 2008 Enterprise Edition (this is a very big file: 3GB). You can download from any computer that has enough space and can allow you to create a DVD. If you are downloading, the file will be saved in your computer. When the download is over, you must create an image. After creating the DVD image, you can insert the DVD in the drive.

Practical Learning: Installing MS SQL Server


1. Start the computer. Using an account with administrative rights, log in, providing a username and a password 2. Insert the DVD in the drive. The installation will start. You may get a message that the .NET Framework needs to be installed. On that message, click OK. You will be prompted to start the installation:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

After clicking the ACCEPT button, you can click Install. The installation of the .NET Framework would start. When the installation of the .NET Framework is over, you would receive a message:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

From there, you can click Exit. You may be asked to install a hotfix:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

In this case, accept to install it by clicking Next and following the wizard. When the installation is over, you may be asked to restart:

Which you should do. 3. To start the installation, put the Microsoft SQL Server 2008 DVD in the drive. A window would come up:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

4. In the left section, click Installation

5. If you are only insterested in studying database design and development in Microsoft SQL Server, on the right side, click New SQL Server Stand-Alone... The installation would start:

6. After the message box, click OK

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

7. Another message box would come up. When it finishes, the next page of the wizard would come up. If you are using the evaluation version, read the message and click Next

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

8. The License Terms page is presented to you. Read it. If you don't agree with the license, click Cancel. Otherwise, click the I Accept check box and click Next:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

9. On the next page, read the messages and click Install:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

10. On the next page, read the messages and click Next:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

11. The next page allows you to specify what you want to install and what would be left out. After making your selections, click Next

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

12. The next page allows you to name the instance and to specify where the server would be installed. After making your selections, click Next:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

13. The next page mostly allows you to check and confirm the disk space. After checking it, click Next

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

14. The next page allows you to configure the server. After making your selections, click Next

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

15. In the next page, specify how authentication would be made. You should also specify the account used as the administrator. To do this, you can click Add Current User. Then click Next

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

16. The next step allows you to specify an account for the analysis services. You can simply click the Add Current User and click Next

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

17. The next page allows you to specify the reporting service to install. Accept the default or make the necessairy change. Then click Next:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

18. The next page allows you to specify whether you want installation information to be collected and sent to Microsoft. After making your choice(s), click Next

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

The pre-installation will proceed and let you know when it ends with the Installation Rules display:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

19. After reading, click Next. This would indicate that the installation is ready to proceed:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

20. To start the installation, you can click Install. The installation would start and the progress bar would indicate the evolution. This can take a while

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

21. When this phase is over, a message box will let you know. After reading it, you can click Next. The last page of the wizard should announce that the installation was complete

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

22. After reading the message, you can click Close

After installing Microsoft SQL Server, you can start using it. Because Microsoft SQL Server works as a service to the operating system, in order to use it, you must make sure its service has started. To check it (on Microsoft Windows XP Professional, Windows Vista, Windows Server 2003, or Windows Server 3008) you can open Control Panel and the Administrative Tools. In the Administrative Tools window, you can open the Services. In the Services window, check the status of the SQL Server (MSSQLSERVER) item:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If the MSSQLSERVER service is stopped, you must start it. To do this, you can right-click it and click Start. If it fails to start, check the account with which you logged in: If you are using Microsoft Windows XP Professional and you logged in as Administrator but did not provide a password, you should open Control Panel, access User Accounts, open the Administrator account, and create a password for it If you are using a server (Microsoft Windows Server 2003 or Microsoft Windows Server 2008), make sure you logged in with an account that can start a service

Once the service has started, it should be labeled Started:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Opening Microsoft SQL Server


To launch Microsoft SQL Server, you can click Start -> (All) Programs -> Microsoft SQL Server 2008 -> SQL Server Management Studio

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

When it starts, it would present a dialog box that expects you to log in.

Practical Learning: Launching Microsoft SQL Server


1. To launch Microsoft SQL Server, click Start -> (All) Programs -> Microsoft SQL Server 2008 > SQL Server Management Studio. A splash screen will appear:

2. On the Connect to Server dialog box, click Cancel

The Microsoft SQL Server Management Studio


Introduction
ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

There are many tools you will use in Microsoft SQL server. One of them is called Microsoft SQL Server Management Studio. To access it, you can click Start -> (All) Programs -> Microsoft SQL Server 2008 -> SQL Server Management Studio. A dialog box would come up but you can click Cancel on it:

The top section of the SQL Server Management Studio displays the classic title bar of a regular window, with an icon on the left, followed by the title of the application, and the system buttons on the right side.

The Main Menu


Under the title bar, the menu bar displays categories of menus that you will use to perform the various necessary operations.

The Standard Toolbar


The Standard toolbar displays under the main menu:

The Standard toolbar is just one of the available ones. Eventually, when you perform an action ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

that would benefit from another toolbar, the Microsoft SQL Server Management Studio would display that toolbar. Still, if you want to show any toolbar, you can right-click any menu item on the main menu or any button on a toolbar. A menu would come up:

The Object Explorer


The left side of the interface displays the Object Explorer window, with its title bar labeled Object Explorer. This window is dockable, meaning you can move it from the left side to another side on the interface. To do this, you can click and drag its title bar to a location of your choice. When you start dragging, small boxes that represent the possible placeholders would come up:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

You can drag and drop to one of those placeholders. The Object Explorer is also floatable, which means you can place it somewhere in the middle of the interface:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

To place the window back to its previous position, you can double-click its title bar. The window can also be tabbed. This means that the window can be positioned either vertically or horizontally. At any time, if you do not want the Object Explorer, you can close or hide it. To close the Object Explorer, click its close button. On the right side of the Object Explorer title, there are three buttons. If you click the first button that points down, a menu would appear:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

The menu allows you to specify whether you want the window to be floated, docked, or tabbed. The right side of the window is made of an empty window. This area will be used to display either the contents of what is selected in the Object Explorer, or to show a result of some operation. As you will see later on, many other windows will occupy the right section but they will share the same area. To make each known it will be represented with a tab and the tab shows the name (or caption) of a window.

Connection to a Server
Using Connect to Server
In order to do anything significant in Microsoft SQL Server, you will have to log in to a server. If you start Microsoft SQL Server Management Studio from the Start button, the Connect To Server dialog box would come up. If you had started from the Start button but clicked Cancel, to connect to a server: On the main menu, click File -> Connect Object Explorer On the Standard toolbar, you can click the New Query button On the Object Explorer, you can click the arrow of the Connect button and click one of the options, such as Database Engine...

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Any of these actions would display the Connect to Server dialog box:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

From there, select the name of the server and the type of authentication to use. If you choose the Windows Authentication, you can just click Connect. Otherwise, in the Authentication combo box, you can select SQL Server Authentication. In this case, you must provide a username and a password:

Once you are ready, click Connect. If you log in successfully, the Object Explorer would appear with a few nodes:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

After using Microsoft SQL Server Management Studio, you can close it. To do this: Click the icon on the left side of Microsoft SQL Server Management Studio and click Close On the right side of the title bar, click the system Close button On the main menu, click File -> Exit Press Alt, F, X

Using the Command Prompt


Besides the SQL Server Management Studio, you can also work on Microsoft SQL Server from the DOS command prompt. This is done using an application or command named SQLCMD.EXE. To use it, open the Command Prompt, type SQLCMD (case-insensitive) and press Enter.

After using Microsoft SQL Server from the command prompt, to close it, type Quit (caseinsensitive) and press Enter. To close the DOS window: Type Exit (case-insensitive) and press Enter Click the system Close button

Using the Windows PowerShell


When Microsoft SQL Server 2008 is installed, it also installs the Windows PowerShell 1.0, which is a new command-based application from Microsoft. Besides the SQL Server Management Studio and the Command Prompt, you can use PowerShell to create and manage databases. To access it, you can click Start -> (All) Programs -> Windows PowerShell 1.0 -> Windows PowerShell. A DOS window would display:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Notice that the title bar displays Windows PowerShell. To access Microsoft SQL Server from PowerShell, type SQLCMD and press Enter:

Notice that, this time, the title bar displays SQLCMD, which indicates that the application is ready to receive commands that relate to Microsoft SQL Server. After using the PowerShell, to exit from Microsoft SQL Server, type Quit (case-insensitive) and press Enter:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

To close PowerShell and the DOS window, you can: Type Exit (case-insensitive) and press Enter Click the system Close button

Using the Microsoft SQL Server Management Studio


Introduction
The Object Explorer displays a list of items as a tree-style. One of the most regularly used items will be the name of the server you are using. If you are just starting to learn database development or you are a junior database developer, you may use or see only one server. In some cases, you may be dealing with many. Regardless, you should always know what server you are currently connecting to. This is easy to check with the first node of the Object Explorer. In the following example, the server is named Central:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

The name of the server is followed by parentheses. In the previous section, we saw that, to establish a connection to a server, you must authenticate yourself. In some cases you may use the same account over and over again. In some other cases you may have different accounts that you use for different scenarios, such as one account for database development, one account for database management, and/or one account for database testing. Some operations cannot be performed by some accounts. When performing some operations, you should always know what account you are using. You can check this in the parentheses of the server name. In the following connection, an account called Administrator is currently logged in to a server named Central:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Object Explorer Details


We saw that, by default, the right area of microsoft SQL Server Management Studio displays an empty gray window. When you select something in the Object Explorer, you can use that right area to display more detailed information about the select item. To do this, on the main menu, you can click View -> Object Explorer Details. The main are on the right side would then be filled with information:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Probably the most regular node you will be interested in, is labeled Databases. This node holds the names of databases on the server you are connected to. Also, from that node, you can perform almost any necessary operation of a database. To see most of the regularly available actions, you can expand the Databases node and some of its children. You can then right-click either Databases or one of its child nodes. For example, to start PowerShell, you can right-click the Databases node or the server name and click PowerShell:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

When the PowerShell comes up, what it displays depends on what you had right-clicked.

Introduction to Code
Although you will perform many of your database operations visually, some other operations will require that you write code. To assist with with this, Microsoft SQL Server provides a code editor and various code templates. To open the editor: On the main menu, you can click File -> New -> Query With Current Connection On the Standard toolbar, click the New Query button In the Object Explorer, right-click the name of the server and click New Query

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

This would create a new window and position it on the right side of the interface. Whether you have already written code or not, you can save the document of the code editor at any time. To save it: You can press Ctrl + S On the main menu, you can click File -> Save SQLQueryX.sql... On the Standard toolbar, you can click the Save button

You will be required to provide a name for the file. After saving the file, its name would appear on the tab of the document.

The Structured Query Language


Introduction

After establishing a connection, you can take actions, such as creating a database and/or manipulating da

The Structured Query Language, known as SQL, is a universal language used on various computer syste manage databases.

SQL can be pronounced Sequel or S. Q. L. In our lessons, we will consider the Sequel pronuncia reason, the abbreviation will always be considered as a word, which would result in A SQL stat of "An SQL statement". Also, we will regularly write, The SQL instead of The SQL language, a represents Language.

Like other non-platform specific languages such as C/C++, Pascal, or Java, the SQL you learn can be a database systems. To adapt the SQL to Microsoft SQL Server, the company developed Transact-SQ implementation of SQL. Transact-SQL is the language used internally by Microsoft SQL Server and MSD Server highly adheres to the SQL standards, it has some internal details that may not be applied to systems like MySQL, Oracle, or even Microsoft Access, etc; although they too fairly conform to the standa

The SQL we will learn and use here is Transact-SQL. In other words, we will assume that you are usin Server as your platform for learning about databases. This means that, unless specified otherwise, mos this site, the word SQL refers to Transact-SQL or the way the language is implemented in Microsoft SQL S

The SQL Interpreter

As a computer language, the SQL is used to give instructions to an internal program called an interpreter in various sections, you must make sure you give precise instructions. SQL is not case-sensitive. CREATE, create, and Create mean the same thing. It is a tradition to write SQL's own words in upperca distinguish SQL instructions with the words you use for your database.

As we will learn in this and the other remaining lessons of this site, you use SQL by writing statements. this, Microsoft SQL Server provides a window, also referred to as the Query Window, that you can use t code. To access it, on the left side of the window, you can right-click the name of the server and click N same way, you can open as many instances as the New Query as you want. ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

When the Query window comes up, it display a blank child window in which you can write your code. Th is a document and it can be saved as a file. The file would have the extension .sql. Every time you open a represented with a tab. To switch from one code part to another, you can click its tab. To dismiss an query, first access it (by clicking its tab), then, on the right side, click the close button . If you had w query window, when you close it, you would be asked to save your code. If you want to preserve your co If you had already executed the code in the window (we will learn how to write and execute SQL code), y save the contents of the window.

Executing a Statement
In the next sections and lessons, we will learn various techniques of creating SQL statements with code. a new query window appears, it is made of a wide white area where you write your statements:

After writing a statement, you can execute it, either to make it active or simply to test it. To execute a st You can press F5 On the main menu, you can click Query -> Execute On the SQL Editor toolbar, you can click the Execute button You can right-click somewhere in the code editor and click Execute

When you execute code, code editor becomes divided into two horizontal sections:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Also, when you execute code, the interpreter would first analyze it. If there is an error, it would display lines of text in its bottom section. Here is an example:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If there is no error in the code, what happens when you execute a statement depends on the code statement.

Accessories for SQL Code Writing

Built-In Functions Fundamentals

Introduction
While your primary job as a database developer consists of creating lists, probably your second most important job is to assist your users with the various assignments they must perform on your application . One way you can assist is to use functions that perform otherwise complex tasks. We ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

introduced and described functions in the previous lesson. To assist your development with the different tasks of a database, Transact-SQL ships with various already created and tested functions. You just need to be aware of these functions, their syntax, and the results they produce. To help you identify the functions you can use, they are categorized by their types and probably their usefulness.

Because of their complexities, some values can be easily recognized or fixed. For example, a date suc 1995 is constant and can never change. This type of value is referred to as deterministic because it is a In the same way, a time value such as 5PM is constant and cannot change. There are other values that c in advance because they change based on some circumstances. For example, the starting date of changes from one year to another but it always occurs. This means that, you know it will happen but you exact date. Such a value is referred to as non-deterministic.

To support determinism and non-determinism, Transact-SQL provides two broad categories of functions always returns the same or known value is referred to as deterministic. A function whose returned value a condition is referred to as non-deterministic.

Casting a Value

In most cases, a value the user submits to your database is primarily considered a string. This is con what you are expecting. If the value the user provides must be treated as something other than a string the user provides a number, before using such a value, you should first convert it to the appropriate type string to the expected type.

To assist with conversion, you can use either the CAST() or the CONVERT() function. The syntax function is: CAST(Expression AS DataType)

The Expression is the value that needs to be cast. The DataType factor is the type of value you wan Expression to. The DataType can be one of those we reviewed in Lesson 4.

In the following example, two variables are declared and initialzed as strings. Because they must b multiplication, each is converted to a Decimal type: DECLARE @StrSalary Varchar(10), @StrHours Varchar(6), @WeeklySalary Decimal(6,2) SET @StrSalary = '22.18'; SET @StrHours = '38.50'; SET @WeeklySalary = CAST(@StrSalary As Decimal(6,2)) * CAST(@StrHours As Decimal(6,2)); SELECT @WeeklySalary; GO Here is an example of executing the above statement:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Converting a Value

Like CAST(), the CONVERT() function is used to convert a value. Unlike CAST(), CONVERT can be u value its original type into a non-similar type. For example, you can use CONVERT to cast a number i vice-versa. The syntax of the CONVERT() function is: CONVERT(DataType [ ( length ) ] , Expression [ , style ])

The first argument must be a known data type, such as those we reviewed in Lesson 4. If you are conv into a string (varchar, nvarchar, char, nchar) or a binary type, you should specify the number of allowe data type's own parentheses. As reviewed for the CAST() function, the Expression is the value th converted. Here is an example: -- Square Calculation DECLARE @Side As Decimal(10,3), @Perimeter As Decimal(10,3), ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

SET SET SET PRINT PRINT PRINT PRINT PRINT GO

@Area As Decimal(10,3); @Side = 48.126; @Perimeter = @Side * 4; @Area = @Side * @Side; 'Square Characteristics'; '-----------------------'; 'Side = ' + CONVERT(varchar(10), @Side, 10); 'Perimeter = ' + CONVERT(varchar(10), @Perimeter, 10); 'Area = ' + CONVERT(varchar(10), @Area, 10);

This would produce:

String-Based Functions
ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Introduction

The string is the most basic, the primary value that is presented to a database. This is because, any val treated particularly, is firstly considered a string. In an application, there are various ways you use or g can get it or provide it to a function as a constant string, that is, a string whose value you know certai pass to a function. You can also get a string that a user provides. Other functions also can produce or ret

To assist you with managing strings or performing operations on them, Transact-SQL provides variou functions can divide in categories that include character-based, conversions, addition, sub-strings, etc.

Practical Learning: Introducing Transact-SQL Functions


1. Start Microsoft SQL Server and connect to the server 2. Right-click the Databases node and click New Database... 3. Set the Name to Exercise1 and click OK 4. Expand the Databases node 5. Expand Exercise1 6. Expand Programmability 7. Expand Functions

The Length of a String

Some operations performed on strings require that you know the number of characters of a string. This operations require a minimum number of characters and some other functions require that the string h character. The number of characters of a string is also called the length of the string. To get the length of a string, you can use the LEN() function. Its syntax is: int LEN(String)

This function takes one argument as the string to be considered. It returns the number of characters in is an example: DECLARE @FIFA varchar(120) SET @FIFA = 'Fdration Internationale de Football Association' SELECT @FIFA AS FIFA SELECT LEN(@FIFA) AS [Number of Characters] This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

String Conversions: Converting From Integer to ASCII

As you may know already, a string is primarily one or a group of characters. These characters are ASC have a string, to get the ASCII code of its leftmost character, you can use the ASCII() function. Its synta int ASCII(String)

This function takes as argument as string and returns the ASCII code of the first (the left) character of th an example: DECLARE @ES varchar(100) SET @ES = 'El Salvador' SELECT @ES AS ES SELECT ASCII(@ES) AS [In ASCII Format] This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

String Conversions: Converting From ASCII to Integer

If you have the ASCII code of a character and want to find its actual character, you can use the CHA syntax is: char CHAR(int value)

This function takes as argument a numeric value as an integer. Upon conversion, the function re equivalent of that number.

String Conversions: Lowercase

As you may know already, a string can be made of uppercase, lowercase, and symbols that don't have a When you receive a string, if you want to convert all of its characters to lowercase, you can use the LO Its syntax is: varchar LOWER(String)

This function takes as argument a string. Any lowercase letter that is part of the string would not change is part of the string would be converted to lowercase. Any other character or symbol would be ke conversion, the LOWER() function returns a new string. ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Here is an example: DECLARE @FIFA varchar(120) SET @FIFA = 'Fdration Internationale de Football Association' SELECT @FIFA AS FIFA SELECT LOWER(@FIFA) AS Converted This would produce:

Practical Learning: Converting a String to Lowercase


1. In the Object Explorer, right-click Exercise1 and click New Query... 2. To create a function, type the following: -- ============================================= -- Function: GetUsername -- ============================================= CREATE FUNCTION GetUsername (@FirstName varchar(40), @LastName varchar(40)) ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

RETURNS varchar(50) AS BEGIN DECLARE @Username AS varchar(50); SELECT @Username = LOWER(@FirstName) + LOWER(@LastName); RETURN @Username; END GO 3. Press F5 to execute the statement 4. Save the code as Exercise 5. Press Ctrl + A to select the code and press Delete to remove the code 6. To test the function, type the following: SELECT Exercise1.dbo.GetUsername('Francine', 'Moukoko'); GO 7. Press F5 to execute the statement

8. In the Object Explorer, expand the Databases node if necessary, and expand Exercise1 9. Expand Programmability 10. Expand Functions 11. Expand Scalar-Valued Functions 12. Right-click dbo.GetUserName and click Delete ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

13. In the Delete Object dialog box, click OK

Sub-Strings: The Starting Characters of a String

A sub-string is a section gotten from a string. The idea is to isolate one or a group of characters fo reason.

A left sub-string is one or a group of characters retrieved from the left side of a known string. To get th of a string, you can use the LEFT() function. Its syntax is: varchar LEFT(String, NumberOfCharacters)

This function takes two arguments. The first argument specifies the original string. The second argum number of characters from the most-left that will constitute the sub-string. After the operation, the returns a new string made of the left character + the NumberOfCharacters on its right from the String.

Practical Learning: Creating a Sub-String With Left Characters


1. Delete the previous code from the query window 2. To use the LEFT() function, type the following: -- ============================================= -- Function: GetUsername -- ============================================= CREATE FUNCTION GetUsername (@FirstName varchar(40), @LastName varchar(40)) RETURNS varchar(50) AS BEGIN DECLARE @Username AS varchar(50); SELECT @Username = LOWER(LEFT(@FirstName, 1)) + LEFT(LOWER(@LastName), 4) RETURN @Username; END GO 3. Press F5 to execute the statement 4. Delete the code in the query window 5. To test the function, type the following: SELECT Exercise1.dbo.GetUsername('Francine', 'Moukoko'); GO 6. Execute the statement in the window

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

7. Change the call with a last name shorter than 5 characters such as "Um" and execute the statement example:

Sub-Strings: The Ending Characters of a String


Instead of the starting characters of a string, you may want to create a string using the most-right ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

existing string. To support this operation, Transact-SQL provides the RIGHT() function. Its syntax is: varchar RIGHT(String, NumberOfCharacters)

This function takes two arguments. The first argument specifies the original string. The second argum number of characters from the most-right that will constitute the sub-string.

Practical Learning: Getting the Right Characters


1. Delete the previous code from the query window 2. To create a function, type the following: -- ============================================= -- Function: Last4DigitsOfSSN -- ============================================= CREATE FUNCTION Last4DigitsOfSSN(@SSN varchar(12)) RETURNS char(4) AS BEGIN RETURN RIGHT(@SSN, 4); END GO 3. Press F5 to execute the statement 4. Delete the previous code from the query window 5. To test the function, type the following: SELECT Exercise1.dbo.Last4DigitsOfSSN('836483846'); GO 6. Execute the statement

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Sub-Strings: Replacing Occurrences in a String

One of the most annoying situations you may encounter with a string is to deal with one that cont characters. This could be due to its formatting or any other reason. For example, if you request a telepho a user, there are various ways the string could be presented to you. Examples are 000-000-0000, or (000) 000-0000. Every one of these formats is an acceptable US and Canadian telephone number but if string in an operation, you could get an unpredictable result. One way you can solve this type of probl any undesired characters from the string. This operation can also consist of replacing some character(s) w

To replace one character or a sub-string from a string, you can use the REPLACE() function. Its syntax i varchar REPLACE(String, FindString, ReplaceWith) or binary REPLACE(String, FindString, ReplaceWith)

This function takes three arguments. The first is the string that will be used as reference. The se FindString, is a character or a sub-string to look for in the String argument. If the FindString character found in the String, then it is replaced with the value of the last argument, ReplaceWith.

Practical Learning: Replacing Characters or Sub-Strings


1. In the Object Explorer, delete dbo.Last4DigitsOfSSN 2. Delete the code in the query window 3. To use the REPLACE() function, change the code as follows: -- ============================================= ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

-- Function: Last4DigitsOfSSN -- ============================================= CREATE FUNCTION Last4DigitsOfSSN(@SSN varchar(12)) RETURNS char(4) AS BEGIN DECLARE @StringWithoutSymbol As varchar(12); -- First remove empty spaces SET @StringWithoutSymbol = REPLACE(@SSN, ' ', ''); -- Now remove the dashes "-" if they exist SET @StringWithoutSymbol = REPLACE(@StringWithoutSymbol, '-', ''); RETURN RIGHT(@StringWithoutSymbol, 4); END GO 4. Execute the statement 5. Delete the code in the query window 6. To test the function, type the following SELECT Exercise1.dbo.Last4DigitsOfSSN('244-04-8502'); GO 7. Execute the statement in the window

Arithmetic Functions
The Sign of a Number

In arithmetic, a number is considered as being negative (less than 0), null (equal to 0), or positive (highe a number is negative, it must have a - symbol to its left. If it is positive, it may display a + symbol to omit it. A number without the - or + symbol to its left is considered positive, also referred to as unsign that determines whether a number is positive or negative is referred to as its sign. The sign is easily know the number already. In some cases, when a number is submitted to your application, before taking may need to get this piece of information.

To find out if a value is positive, null, or negative, Transact-SQL provides the SIGN() function. Its syntax SIGN(Expression)

This function takes as argument a number or an expression that can be evaluated to a number. The in then examine the number: If the Expression is positive, the function returns 1. Here is an example: DECLARE @Number As int; SET @Number = 24.75; SELECT SIGN(@Number) AS [Sign of 1058]; GO ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If the Expression is null, the function returns 0 DECLARE @Number As int; SET @Number = 0; SELECT SIGN(@Number) AS [Sign of Number]; GO

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If the Expression is negative, the function returns -1 DECLARE @Number As int; SET @Number = -57.05; SELECT SIGN(@Number) AS [Sign of -57.05]; GO

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Based on this, you can use the SIGN() function to find out whether a value is negative, null, or positive: value (or a variable) to SIGN() and use a logical operator to check its sign. Here is an example: -- Square Calculation DECLARE @Side As Decimal(10,3), @Perimeter As Decimal(10,3), @Area As Decimal(10,3); SET @Side = 48.126; SET @Perimeter = @Side * 4; SET @Area = @Side * @Side; IF SIGN(@Side) > 0 BEGIN PRINT 'Square Characteristics'; PRINT '-----------------------'; PRINT 'Side = ' + CONVERT(varchar(10), @Side, 10); PRINT 'Perimeter = ' + CONVERT(varchar(10), @Perimeter, 10); PRINT 'Area = ' + CONVERT(varchar(10), @Area, 10); END; ELSE PRINT 'You must provide a positive value'; GO Here is an example of executing the statement:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Here is another example of executing the statement:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Notice that the interpreter acts differently in response to the result of the SIGN() function.

The Absolute Value of a Number

The decimal numeric system counts from minus infinity to infinity. This means that numbers are usu positive, depending on their position from 0, which is considered as neutral. In some operations, the nu will need to be only positive even if it is provided in a negative format. The absolute value of a num number is (already) positive. If the number is negative, its absolute value is its positive equivalent. F absolute value of 12 is 12, while the absolute value of 12 is 12. To get the absolute value of a number, you can use the ABS() function. Its syntax is: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

ABS(Expression)

This function takes an expression or a number as argument and returns its absolute value. Here is an exa DECLARE @NumberOfStudents INTEGER; SET @NumberOfStudents = -32; SELECT ABS(@NumberOfStudents) AS [Number of Students]; GO This would produce:

The Ceiling of a Number


Consider a decimal value such as 12.155. This number is between integer 12 and integer 13

In the same way, consider a number such as 24.06. As this number is negative, it is between 24 an being greater. ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

In algebra, the ceiling of a number is the closest integer that is greater than or higher than the numbe the first case, the ceiling of 12.155 is 13 because 13 is the closest integer greater than or equal to 12.15 24.06 is 24. To get the ceiling of a number, Transact-SQL provides the CEILING() function. Its syntax is: CEILING(Expression)

This function takes as argument a number or an expression that can evaluate to a number. After the c function succeeds, it returns a double-precision number that is greater than or equal to Expression. Here DECLARE @Number1 As Numeric(6, 2), @Number2 As Numeric(6, 2) SET @Number1 = 12.155; SET @Number2 = -24.06; SELECT CEILING(@Number1) AS [Ceiling of 12.155], CEILING(@Number2) AS [Ceiling of 24.06]; GO This would produce:

Here is another way of displaying the above results: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

DECLARE @Number1 As Numeric(6, 2), @Number2 As Numeric(6, 2) SET @Number1 = 12.155; SET @Number2 = -24.06; PRINT 'The ceiling of 12.155 is ' + CONVERT(varchar(10), CEILING(@Number1)); PRINT 'The ceiling of 24.06 is ' + CONVERT(varchar(10), CEILING(@Number2)); GO This would produce:

The Floor of a Number

Consider two decimal numbers such as 128.44 and -36.72. The number 128.44 is between 128 and 129 the lower. The number 36.72 is between 37 and 36 with 37 being the lower. The lowest but closest a number is referred to as its floor. Based on this, the floor of 128.44 is 128. The floor of 36.72 is 37. To support finding the floor of a number, Transact-SQL provides the FLOOR() function. Its syntax is: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

FLOOR(Expression)

The FLOOR() function takes as argument a numeric value or an expression that can be evaluated to a function succeeds during its conversion, it produces the integer that is the floor of the argument. Here is DECLARE @Number1 As Numeric(6, 2), @Number2 As Numeric(6, 2); SET @Number1 = 128.44; SET @Number2 = -36.72; SELECT FLOOR(@Number1) AS [Floor of 128.44], FLOOR(@Number2) AS [Floor of 36.72]; GO This would produce:

The Exponent of a Number


EXP(Expression) ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

To calculate the exponential value of a number, Transact-SQL provides the EXP() function. Its syntax is:

This function takes one argument as a number or an expression that can be evaluated to a number. Here DECLARE @Number As Numeric(6, 2); SET @Number = 6.48; SELECT EXP(@Number) AS [Exponent of 6.48]; GO This would produce:

The Power of a Number

The power of a number is the value of that number when raised to another number. This is done usi formula: ReturnValue = xy To support finding the power of a number, Transact-SQL provides the POWER() function. Its syntax is: POWER(x, y)

This function takes two required arguments. The first argument, x, is used as the base number to be second argument, y, also called the exponent, will raise x to this value. Here is an example: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

DECLARE @x As Decimal(6, 2), @y As Decimal(6, 2); SET @x = 20.38; SET @y = 4.12; SELECT POWER(@x, @y) AS [Power of 20.38 raised to 4.12]; GO This would produce:

The Natural Logarithm of a Number


LOG(Expression)

To assist with finding the natural logarithm of a number, Transact-SQL provides the LOG() function. Its s

This function takes one argument as a number or an expression that can evaluate to a number. After t returns the natural logarithm of the argument. Here is an example: DECLARE @Number As Decimal(6, 2); SET @Number = 48.16; SELECT LOG(@Number) AS [Natural Logarithm of 48.16]; GO This would produce: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

The Base-10 Logarithm of a Number


LOG10(Expression)

To calculate the base 10 logarithm of a number, Transact-SQL provides the LOG10() function. Its syntax

The number to be evaluated is passed as the argument X. The function returns the logarithm on ba formula: y = log10x which is equivalent to x = 10y Here is an example: DECLARE @Number As Decimal(6, 2); SET @Number = 48.16; SELECT LOG10(@Number) AS [Base-10 Logarithm of 48.16]; GO This would produce: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

The Square Root


To support the calculation of a square root, Transact-SQL provides the SQRT() function. Its syntax is: SQRT(Expression)

This function takes one argument as a positive decimal number. If the number is positive, after the function returns the square root of x. Here is an example: DECLARE @Number As Decimal(6, 2); SET @Number = 48.16; SELECT SQRT(@Number) AS [The square root of 48.16 is]; GO This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If the number is negative, you would receive an error. Here is an example:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

In this case, you can use a control statement to find out whether the Expression is positive. Here is an ex DECLARE @Number As Decimal(6, 2); SET @Number = 258.4062; IF SIGN(@Number) > 0 PRINT 'The square root of 258.4062 is ' + CONVERT(varchar(12), SQRT(@Number)); ELSE PRINT 'You must provide a positive number'; GO Here is one example of executing the statement:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Here is another example of executing the statement:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Measure-Based Functions
Introduction

A circle is a series of distinct opposite points positioned each at an exact same distance from another poi the center. The distance from the center C to one of these equidistant points is called the radius, connects all of the points that are equidistant to the center is called the circumference of the circle. The distance between two points of the circumference to the center. In other words, a diameter is double the ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

To manage the measurements and other related operations, the circumference is divided into 360 portion portions is called a degree. The unit used to represent the degree is the degree, written as . Therefore, 360 degrees, that is 360. The measurement of two points A and D of the circumference could have 15 circumference. In this case, this measurement would be represents as 15.

The distance between two equidistant points A and B is a round shape geometrically defined as an arc. ratio of the distance between two points A and B of the circumference divided by the radius R. This can b

PI

The letter , also written as PI, is a number used in various mathematical calculations. Its appro 3.1415926535897932. The calculator of Microsoft Windows represents it as 3.141592653589793238462 get the value of PI, Transact-SQL provides the PI() function. Its syntax is simply: PI()

Radians

An angle is the ratio of an arc over the radius. Because an angle is a ratio and not a physical mea means an angle is not a dimension, it is independent of the size of a circle. Obviously the angle represen portions covered by three points. A better unit used to measure an angle is the radian or rad. If you know the value of an angle in degrees and you want to get the radians, Transact-SQL provides function. Its syntax is: RADIANS(Expression)

This function takes as argument a value in degrees. If it succeeds in its calculation, it returns the radians

A cycle is a measurement of the rotation around the circle. Since the rotation is not necessarily complet the scenario, a measure is made based on the angle that was covered during the rotation. A cycle could circle, in which case the rotation would not have been completed. A cycle could also cover the whole 3 and continue there after. A cycle is equivalent to the radian divided by 2 * Pi.

Degrees
ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If you know the radians but want to get the degrees of an angle, you can use the DEGREES() function. I DEGREES(Expression)

This function takes as argument a value in radians. If it succeeds, it returns the equivalent value in degre

Trigonometric Functions
The Cosine of a Value

Consider AB the length of A to B, also referred to as the hypotenuse. Also consider AC the length of A t side adjacent to point A. The cosine of the angle at point A is the ratio AC/AB. That is, the ratio of the AC, over the length of the hypotenuse, AB:

The returned value, the ratio, is a double-precision number between 1 and 1. To get the cosine of an angle, you can call the COS() function. Its syntax is: COS(Expression)

The angle to be considered is passed as the argument to this function. The function then calculates cosine. Here is an example: DECLARE @Angle As Decimal(6, 3); SET @Angle = 270; SELECT COS(@Angle) AS [Cosine of 270]; GO This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

The Sine of a Value

Consider AB the length of A to B, also called the hypotenuse to point A. Also consider CB the length of the opposite side to point A. The sine represents the ratio of CB/AB; that is, the ratio of the opposite s hypotenuse AB. To get the sine of an angle, you can use the SIN() function whose syntax is: SIN(Expression)

The angle to be considered is passed as the argument. After its calculation, the function returns the s between 1 and 1. Here is an example: DECLARE @Angle As Decimal(6, 3); SET @Angle = 270; SELECT SIN(@Angle) AS [Sine of 270]; ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

GO This would produce:

The Tangent of a Value

In geometry, consider AC the length of A to C. Also consider BC the length of B to C. The tangent is the that is, the ratio of BC over AC. To get the tangent of an angle, you can use the TAN() function of Transact-SQL. Its syntax is: TAN(Expression) Here is an example: DECLARE @Angle As Decimal(6, 3); SET @Angle = 270; SELECT TAN(@Angle) AS [Tangent of 270]; GO ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

This would produce:

Date and Time Based Functions


Introduction

Date and time values are highly used in database applications. They involve sales, time sheets, taxes, etc. Based on this usefulness, their operations are supported by various libraries you will be using when application. Without being the most elaborate on this issue, Transact-SQL provides its own level of supp time values.

Before using a date or a time value in a calculation, remember that you must first get it one way or a define a date or a time constant in your application. An example would be '1992/10/28'. You can declare a SmallDateTime variable and initialize it as you see fit. You may get a date or a time from another fun alternative, you may get a date or time from another application or from a user. Once you have an appro can use it.

The Current System Date and/or Time

One of the ways you can assist the user with date and time is to get the current date or the current time you create a time sheet, when the user starts using it, it would be convenient to fill part of the time predictable values. ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

To get the current date and the current time of the computer that a user is using, you can use the GET of Transact-SQL. Its syntax is: GETDATE() This function simply returns the current date and time of the operating system.

Date/Time Addition

One of the primary operations you may want to perform on a date or a time value would consist of add To support this operation, Transact-SQL provides the DATEADD() function. Its syntax is: DATEADD(TypeOfValue, ValueToAdd, DateOrTimeReferenced)

The third argument to this function is the value of a date or a time on which the operation will be perfor constant value in the form of 'year/month/day' for a date or 'hour:minutes AM/PM' for a time.

The second argument is the value that will be added. It should be a constant integer, such as 8, or a floa such as 4.06.

When calling this function, you must first specify the type of value that you want to add. This type is pa argument. It is used as follows:

If you want to add a number of years to a date, specify the TypeOfValue as Year or yy, or yyyy (re SQL is case-insensitive). Here is an example: DECLARE @Anniversary As DateTime; SET @Anniversary = '2002/10/02'; SELECT DATEADD(yy, 4, @Anniversary) AS Anniversary; GO

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If you want to add a number of quarters of a year to a date, specify the TypeOfValue as Quarter or is an example: DECLARE @NextVacation As DateTime; SET @NextVacation = '2002/10/02'; SELECT DATEADD(Quarter, 2, @NextVacation) AS [Next Vacation]; GO

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If you want to add a number of months to a date, specify the TypeOfValue as Month or m, or mm. example adds 5 months to its date: DECLARE @SchoolStart As DateTime; SET @SchoolStart = '2004/05/12'; SELECT DATEADD(m, 5, @SchoolStart) AS [School Start]; GO

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

In the same way, you can add values as follows: Type of Value Year quarter Month dayofyear Day Week Hour minute Abbreviation yy yyyy q qq m mm y dy d dd wk ww hh n mi As a result A number of years will be added to the date value A number of quarters of a year will be added to the date value A number of months will be added to the date value A number of days of a year will be added to the date value A number of days will be added to the date value A number of weeks will be added to the date value A number of hours will be added to the time value A number of minutes will be added to the time value

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

second millisecond

s ss ms

A number of seconds will be added to the time value A number of milliseconds will be added to the time value

Date/Time Subtraction

Another regular operation performed on a date or a time value consists of getting the number of units tha the range of two dates or two time values. To support this operation, Transact-SQL provides the DATED Its syntax is: DATEDIFF(TypeOfValue, StartDate, EndDate)

This function takes three arguments. The second argument is the starting date or the starting time of considered. The third argument is the end or last date or time of the considered range. You use the f specify the type of value you want the function to produce. This argument uses the same value DATEADD() function: Type of Value Year quarter Month dayofyear Day Week Hour minute second millisecond Abbreviation yy yyyy q qq m mm y dy d dd wk ww hh n mi s ss ms As a result The function will return the number of years that have elapsed between the start and the end dates

The function will return the number of quarters of a year that have elapsed between the start and the end dates The function will return the number of months that have elapsed between the start and the end dates The function will return the number of days of a year that have elapsed between the start and the end dates

The function will return the number of days that have elapsed between the start and the end dates The function will return the number of weeks that have elapsed between the start and the end dates The function will return the number of hours that have elapsed between the start and the end times or dates The function will return the number of minutes that have elapsed between the start and the end times or dates The function will return the number of seconds that have elapsed between the start and the end times or dates The function will return the number of milliseconds that have elapsed between the start and the end times or dates

Here is an example that calculates the number of years that an employees has been with the company: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

DECLARE @DateHired As DateTime,; @CurrentDate As DateTime; SET @DateHired = '1996/10/04'; SET @CurrentDate = GETDATE(); SELECT DATEDIFF(year, @DateHired, @CurrentDate) AS [Current Experience]; GO This would produce:

To rename a column, first open an empty query window. In a query window, 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. ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Here is an example: sp_rename 'StaffMembers.FullName', 'EmployeeName', 'COLUMN'

Variables and Data Types


Variables Fundamentals
Introduction
In the previous lesson, we used some values such as 242 or 'James Knight'. These types of values are referred to as constant because we certainly know them before their use and we don't change them in our statements. If you intend to use a certain category of value over and over again, you can reserve a section of memory for that value. This allows you to put the value in an area of the computer's memory, easily change the value for another, over and over. To use the same area of memory to store and remove values as needed, the SQL interpreter needs two primary pieces of information: a name and the desired amount of space in memory capable of storing the value. Practical Learning: Starting the Management Studio 1. To launch Microsoft SQL Server, click Start -> (All) Programs -> Microsoft SQL Server 2008 -> SQL Server Management Studio 2. On the Connect to Server dialog box, make the correct selections and provide the appropriate information, then click Connect 3. To open the code editor, on the main menu, click File -> New -> Query With Current Connection

Declaring Variables

A variable is an area of memory used to store values that can be used in a program. Before using a va inform the interpreter. This is also referred to as declaring a variable. To declare a variable, use the DE using the following formula: DECLARE Options

The DECLARE keyword lets the interpreter know that you are making a declaration. The DECLARE key by a name for the variable. In Transact-SQL, the name of a variable starts with the @ sign. The name of you to identify the area of memory where the value of the variable is stored. While other languages like Java, C#, etc, impose strict rules to names, Transact-SQL is extremely flexible. A name can be made of is an example: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

DECLARE @264 Such a name made of digits can create confusion with a normal number. A name can also be made words.

Objects Names
To avoid confusion, here are the rules we will use in our lessons: A name will start with either an underscore or a letter. Examples are @_n, @act, or @Second

After the first character as an underscore or a letter, the name will have combinations of underscore digits. Examples are @_n24 or @act_52_t A name will not include special characters such as !, @, #, $, %, ^, &, or *

If the name is a combination of words, each word will start in uppercase. Examples are @DateHired @_RealSport, or @DriversLicenseNumber

To declare a variable, as we will see in the next sections, after giving a name to a variable, you must amount of memory that the variable would need. The amount of memory is also called a data type declaration of a variable uses the following formula: DECLARE @VariableName DataType;

You can also declare more than one variable. To do that, separate them with a comma. The formula woul DECLARE @Variable1 DataType1, @Variable2 DataType2, @Variable_n DataType_n;

Unlike many other languages like C/C++, C#, Java, or Pascal, if you declare many variables that use type, the name of each variable must be followed by its own data type.

Initializing a Variable

After declaring a variable, the interpreter reserves a space in the computer memory for it but th necessarily hold a recognizable value. This means that, at this time, the variable is null. One way you ca to give a value to the variable. This is referred to as initializing the variable.

Remember that a variable's name starts with @ and whenever you need to refer to the variable, you you include the @ sign. To initialize a variable, in the necessary section, type the SELECT or the SET k by the name of the variable, followed by the assignment operator "=", followed by an appropriate val used is: SELECT @VariableName = DesiredValue or SET @VariableName = DesiredValue

Once a variable has been initialized, you can make its value available or display it. This time, you can t the variable to the right side of PRINT or SELECT.

Data Types
ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Introduction

After setting the name of a variable, you must specify the amount of memory that the variable will n value. Since there are various kinds of information a database can deal with, SQL provides a set of data t

Boolean Variables

A Boolean value is a piece of information stated as being true or false, On or Off, Yes or No, 1 or 0. To d that holds a Boolean value, you can use the BIT or bit keyword. Here is an example: DECLARE @IsOrganDonor bit;

After declaring a Boolean variable, you can initialize it with 0 or another value. If the variable is init receives the Boolean value of False. If it is initialized with any other number, it receives a True value. He of using a Boolean variable:

Practical Learning: Using Boolean Variables


1. In the Query window, type the following: DECLARE @IsMarried bit SET @IsMarried = 1 SELECT @IsMarried AS [Is Married?]; GO 2. Execute the statement

Integer Variables

An integer, also called a natural number, or a whole number, is a number that can start with a + or a - s of digits. Between the digits, no character other than a digit is allowed. In the real world, when a numb and becomes difficult to read, such as 79435794, you are allowed to type a symbol called the thousand s thousand increment. An example is 79,435,794. In your SQL expressions, never include the thousand would receive an error. ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

When the number starts with +, such as +44 or +8025, such a number is referred to as positive and you starting + sign. This means that the number should be written as 44 or 8025. Any number that starts wi digit is considered as greater than 0 or positive. A positive integer is also referred to as unsigned. On th number that starts with a - symbol is referred to as negative.

If a variable would hold natural numbers in the range of -2,147,483,648 to 2,147,483,647, you can de int keyword as data type. Here is an example: DECLARE @Category int; SET @Category = 1450; PRINT @Category; GO This would produce 1450:

The length of an integer is the number of bytes its field can hold. For an int type, that would be 4 bytes.

If you want to use very small numbers such as student's ages, or the number of pages of a brochure or the tinyint data type. A variable with the tinyint data type can hold positive numbers that range from 0 an example:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

The smallint data type follows the same rules and principles as the int data type except that it is used numbers that would range between -32,768 and 32,767. Here is an example: 1> DECLARE @NumberOfPages SMALLINT; 2> SET @NumberOfPages = 16; 3> SELECT @NumberOfPages AS [Number of Pages]; 4> GO Number of Pages --------------16 (1 rows affected) The bigint data type follows the same rules and principles as the int data type except that it can numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Here is an example: 1> DECLARE @CountryPopulation BigInt; 2> SET @CountryPopulation = 16500000; 3> SELECT @CountryPopulation AS 'Country Population'; 4> GO Country Population -------------------16500000 (1 rows affected)

The binary data type is used for a variable that would hold hexadecimal numbers. Examples of hexadecim 0x7238, 0xFA36, or 0xAA48D. Use the binary data type if all values of the variable would have the exact quantity). If you anticipate that some entries would be different than others, then use the alternative type. The varbinary type also is used for hexadecimal numbers but allows dissimilar entries, as long a hexadecimals.

Practical Learning: Using Integer Variables


1. Change the statement as follows: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

DECLARE @IsMarried bit, @EmplStatus int; SET @IsMarried = 1; SET @EmplStatus = 2; SELECT @IsMarried AS [Is Married?], @EmplStatus AS [Employment Status]; GO 2. Execute the statement:

Decimal Variables

A decimal number is a number that can have a period (or the character used as the decimal separat Control Panel) between the digits. An example would be 12.625 or 44.80. Like an integer, a decimal n with a + or just a digit, which would make it a positive number. A decimal number can also start with a would make it a negative number. If the number represents a fraction, a period between the digits speci of 1 was cut. If you anticipate such a number for a field, specify its data type as numeric or decimal (e numeric would produce the same effect in SQL Server). Here is an example: 1> DECLARE @Distance DECIMAL; 2> SET @Distance = 648.16; 3> PRINT @Distance; 4> GO 648 ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

A floating-point number is a fractional number, like the decimal type. Floating-point numbers can be u allow the database engine to apply an approximation to the actual number. To declare such a variable, the real keyword. Here is an example: 1> DECLARE @Radius FLOAT; 2> SET @Radius = 48.16; 3> SELECT @Radius AS Radius; 4> GO Radius -----------------------48.159999999999997 (1 rows affected)

A precision is the number of digits used to display a numeric value. For example, the number 42005 has while 226 has a precision value of 3. If the data type is specified as an integer (the int and its varian point number (float and real), the precision is fixed by the database and you can just accept the v Microsoft SQL Server interpreter. For a decimal number (decimal or numeric data types), Microsoft SQ you to specify the amount of precision you want. The value must be an integer between 1 and 38 (28 SQL Server 7).

A decimal number is a number that has a fractional section. Examples are 12.05 or 1450.4227. The sca the number of digits on the right side of the period (or the character set as the separator for decimal n language, as specified in Control Panel). The scale is used only for numbers that have a decimal part currency (money and smallmoney) and decimals (numeric and decimal). If a variable is declared with numeric data type, you can specify the amount of scale you want. The value must be an integer between is an example:

Practical Learning: Using Decimal Variables


1. Change the statement as follows: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

DECLARE @IsMarried bit, @EmplStatus int, @WeeklyHours Decimal(6,2); SET @IsMarried = 1; SET @EmplStatus = 2; SET @WeeklyHours = 36.50; SELECT @IsMarried AS [Is Married?], @EmplStatus AS [Employment Status], @WeeklyHours AS Hours; GO 2. Execute the statement

Currency Variables

If a variable would hold monetary values, you can declare it with the money keyword. A variable with type can hold positive or negative values from -922,337,203,685,477.5808 to +922,337,203,685,477.5 example: 1> DECLARE @YearlyIncome Money; 2> SET @YearlyIncome = 48500.15; 3> SELECT @YearlyIncome AS [Yearly Income]; 4> GO Yearly Income --------------------48500.1500 (1 rows affected)

While the money data type can be used for a variable that would hold large quantities of curre smallmoney data type can be applied for a variable whose value cannot be lower than -214,748.3648 214,748.3647.

The precision and scale of a money or smallmoney variable are fixed by Microsoft SQL Server. The scal

Practical Learning: Using Currency Variables


1. Change the statement as follows: DECLARE @EmplStatus int, @IsMarried bit, @WeeklyHours Decimal(6,2), @HourlySalary SmallMoney, @WeeklySalary SmallMoney; SET @IsMarried = 1; SET @EmplStatus = 2; SET @WeeklyHours = 36.50; SET @HourlySalary = 15.72; SET @WeeklySalary = @WeeklyHours * @HourlySalary; SELECT @EmplStatus AS [Empl Status], ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

@IsMarried AS [Married?], @WeeklyHours AS Hours, @HourlySalary AS Hourly, @WeeklySalary AS Weekly; GO 2. Execute the statement

Date and Time Variables

A DATETIME data type is used for a column whose data would consist of date and/or time values. The valid date or time values but Microsoft SQL Server allows a lot of flexibility, even to display a date in ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

format. The date value of a datetime field can be comprised between January 1st, 1753 and December 3

To initialize a DATETIME variable, include its value between single-quote. If the value is a dat components of the value with the symbol recognized in Control Panel as the Date Separator:

Here is an example: 1> DECLARE @IndependenceDay DATETIME; 2> SET @IndependenceDay = '01/01/1960'; 3> SELECT @IndependenceDay AS [Independence Day]; 4> GO Independence Day ----------------------1960-01-01 00:00:00.000 (1 rows affected)

If the value is a time period, still include it in single-quotes. Inside of the quotes, follows the rules and f in the Control Panel: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Here is an example: 1> DECLARE @ArrivalTime datetime; 2> SET @ArrivalTime = '18:22'; 3> SELECT @ArrivalTime AS [Arrival Time]; 4> GO Arrival Time ----------------------1900-01-01 18:22:00.000 (1 rows affected)

The smalldatetime data type is an alternative to datetime. It follows the same rules and principles a data type except that a date value must be comprised between January 1st, 1900 and June 6, 2079.

Practical Learning: Using Date/Time Variables


1. Change the statement as follows: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

DECLARE @DateHired DateTime, @EmplStatus int, @IsMarried bit, @WeeklyHours Decimal(6,2), @HourlySalary SmallMoney, @WeeklySalary SmallMoney; SET @DateHired = '12/05/1998'; SET @IsMarried = 1; SET @EmplStatus = 2; SET @WeeklyHours = 36.50; SET @HourlySalary = 15.72; SET @WeeklySalary = @WeeklyHours * @HourlySalary; SELECT @DateHired AS [Date Hired], @EmplStatus AS [Empl Status], @IsMarried AS [Married?], @WeeklyHours AS Hours, @HourlySalary AS Hourly, @WeeklySalary AS Weekly; GO 2. Execute the statement

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Character Variables

A field of characters can consist of any kinds of alphabetical symbols in any combination, readable or no variable to hold a fixed number of characters, such as the book shelf numbers of a library, declare it wit type. Here is an example: DECLARE @Gender char;

By default, the char data type can be applied to a variable that would hold one character at a time. Af variable, when initializing it, include its value in single-quotes. Here is an example: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

1> DECLARE @Gender char; 2> SET @GENDER = 'M'; 3> SELECT @Gender AS Gender; 4> GO Gender -----M (1 rows affected) If you include more than one character in the single-quotes, only the first (most left) character would variable. Here is an example: 1> DECLARE @Gender char; 2> SET @Gender = 'Male'; 3> SELECT @Gender AS Gender; 4> GO Gender -----M (1 rows affected)

A string is a character or a combination of characters. If a variable will hold strings of different lengths the varchar data type. The maximum length of text that a field of varchar type can hold is equivalent to

In some circumstances, you will need to change or specify the number of characters used in a string vari First Name and a Book Title variables should use the varchar type, both variables would not have the entries. As it happens, people hardly have a first name that is beyond 20 characters and many book titl characters. In this case, both variables would use the same data type but different lengths.

To specify the maximum number of characters that can be stored in a string variable, on the right varchar, type an opening and a closing parentheses. Inside of the parentheses, type the desired num the variable, if you are using the Command Prompt (SQLCMD.EXE), include its value between double-qu example:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If you are using a query window, don't include the string value in double-quotes; otherwise, you would re

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Therefore, if using the query window, include the string in single-quotes:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

The text data type can be used on a variable whose data would consist of ASCII characters. As oppos type of field, a text type of field can hold text that is longer than 8 kilobytes.

The nchar, nvarchar, and ntext types follow the same rules as the char, varchar, and text respectiv they can be applied to variables that would hold international characters, that is, characters of language English. This is done following the rules of Unicode formats.

Practical Learning: Using Character Variables


1. Change the statement as follows: DECLARE @FirstName varchar(20), @LastName varchar(20), @FullName varchar(40), @DateHired DateTime, @EmplStatus int, @IsMarried bit, @WeeklyHours Decimal(6,2), @HourlySalary SmallMoney, @WeeklySalary SmallMoney; SET @FirstName = 'Samuel'; SET @LastName = 'Weinberg'; ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

SET @FullName = @LastName + ', ' +@FirstName; SET @DateHired = '12/05/1998'; SET @IsMarried = 1; SET @EmplStatus = 2; SET @WeeklyHours = 36.50; SET @HourlySalary = 15.72; SET @WeeklySalary = @WeeklyHours * @HourlySalary; SELECT @FullName As [Full Name], @DateHired AS [Date Hired], @EmplStatus AS [Empl Status], @IsMarried AS [Married?], @WeeklyHours AS Hours, @HourlySalary AS Hourly, @WeeklySalary AS Weekly; GO 2. Execute the statement

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

3. Save the file as Variables in your My Documents folder

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Equality Operator =
To compare two values for equality, use the = operator. Its formula is: Value1 = Value2

The equality operation is used to find out whether two values are the same. From the above formula, would compare Value1 and Value2. If Value1 and Value2 are the same, the comparison produces a TRU different, the comparison renders FALSE. The equality operation can be illustrated as follows:

Not Equal <>


As opposed to equality, to find out if two values are not equal, use the <> operator. Its formula is: Value1 <> Value2

The <> is a binary operator (like all logical operators) that is used to compare two values. The values variables as in Variable1 <> Variable2. Upon comparing the values, if both hold different values, the com TRUE. Otherwise, the comparison renders FALSE or a null value.

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

It can be illustrated as follows:

Notice that the Not Equal operator <> is the opposite to the Equality operator =.

Less Than <


To find out whether one value is lower than another, use the < operator. Its formula is: Value1 < Value2

The value held by Value1 is compared to that of Value2. As it would be done with other operations, the made between two variables, as in Variable1 < Variable2. If the value held by Value1 is lower than comparison produces a true or positive result. The Less Than operator "<" can be illustrated as follows:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Less Than Or Equal To <=

The Equality and the Less Than operators can be combined to compare two values. This allows you to kno the same or if the first is less than the second. The operator used is <= and its formula is: Value1 <= Value2

If both Value1 and Value2 are the same, the result is true or positive. If the left operand, in this case Va lower than the second operand, in this case Value2, the result is still true. If the value of Value1 is stric of Value, the comparison produces a FALSE result. A <= operation can be illustrated as follows:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Greater Than >


To find out if one value is strictly greater than another, you can use the > operator. Its formula is: Value1 > Value2

Both operands, in this case Value1 and Value2, can be variables or the left operand can be a varia operand is a constant. If the value on the left of the > operator is greater than the value on the right sid comparison produces a true or positive value. Otherwise, the comparison renders false or null. The > operator can be illustrated as follows:

Notice that the > operator is the opposite to <=.

Greater Than or Equal To >=


The greater than and the equality operators can be combined to produce an operator as follows: >=. than or equal to" operator. Its formula is: Value1 >= Value2

The comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Va the comparison produces a true or positive value. If the value of the left operand is greater than that of the comparison produces true or positive also. If the value of the left operand is strictly less than the operand, the comparison produces a false or null result. This can be illustrated as follows:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Notice that the >= operator is the opposite to <.

Conditional Statements
Introduction

A condition statement is an expression you formulate to evaluate it. Most of the time, the statement when evaluated, it can produce a result of true or false, then, depending on the outcome, you can take a usually written as simple as possible to make it clear to you and the SQL interpreter. Although the int confused, if you create a difficult statement, you may receive an unpredictable result.

In the next few sections, we will review the keywords and formulas that Transact-SQL provides to help expressions. Expressions usually start with a keyword, followed by the expression itself. After the expr the interpreter what to do. The statement may appear as follows: Keyword Expression Statement

BEGIN...END

With the above formula, we will always let you know what keyword you can use, why, and when. After can write the statement in one line. This is the statement that would be executed if/when the Expressio satisfied. In most cases, you will need more than one line of code to specify the Statement.

As it happens, the interpreter considers whatever comes after the Statement as a unit but only the lin the Expression. To indicate that your Statement covers more than one line, start it with the BEGIN must use the END keyword to indicate where the Statement ends. In this case, the formula of a co would appear as follows: Keyword Expression BEGIN Statement Line 1 ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Statement Line 2 Statement Line n END You can still use the BEGIN...END combination even if your Statement covers only one line: Keyword Expression BEGIN Statement END

Using the BEGIN...END combination makes your code easier to read because it clearly indicates the s Statement.

IF a Condition is True

Probably the primary comparison you can perform on a statement is to find out whether it is true performed using an IF statement in Transact-SQL. Its basic formula is: IF Condition Statement

When creating an IF statement, first make sure you provide a Condition expression that can be evalua or false. To create this Condition, you can use variables and the logical comparison operator reviewed abo

When the interpreter executes this statement, it first examines the Condition to evaluate it to a true res produces true, then the interpreter executes the Statement. Here is an example: DECLARE @DateHired As DateTime, @CurrentDate As DateTime SET @DateHired = '1996/10/04' SET @CurrentDate = '2007/04/11' IF @DateHired < @CurrentDate PRINT 'You have the experience required for a new promotion in this job' GO This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

IF...ELSE

The IF condition we used above is appropriate when you only need to know if an expression is true. The in other alternatives. Consider the following code: DECLARE @DateHired As DateTime, @CurrentDate As DateTime SET @DateHired = '1996/10/04' SET @CurrentDate = '2007/04/16' IF @DateHired > @CurrentDate PRINT 'You have the experience required for a new promotion' GO This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Notice that, in case the expression to examine produces a false result, there is nothing to do. Sometimes

CASE...WHEN...THEN

The CASE keyword is used as a conditional operator that considers a value, examines it, and acts on a on the value. The formula of the CASE statement is: CASE Expression WHEN Value1 THEN Result WHEN Value2 THEN Result WHEN Value_n THEN Result END

In the following example, a letter that represents a student is provided. If the letter is m or M, a string is the value is provided as f or F, a string is created as Female: DECLARE @CharGender Char(1), @Gender Varchar(20); SET @CharGender = 'F'; SET @Gender = CASE @CharGender WHEN 'm' THEN 'Male' WHEN 'M' THEN 'Male' WHEN 'f' THEN 'Female' ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

WHEN 'F' THEN 'Female' END; SELECT 'Student Gender: ' + @Gender; GO Here is the result of executing it:

CASE...WHEN...THEN...ELSE

In most cases, you may know the only types of value that would be submitted to a CASE statement. In an unpredictable value may be submitted. If you anticipate a value other than those you are aware of, t provides a "fit-all' alternative by using the last statement as ELSE. In this case, the formula of the CAS be: CASE Expression ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

WHEN Value1 THEN Result WHEN Value2 THEN Result WHEN Value_n THEN Result ELSE Alternative END

The ELSE statement, as the last, is used when none of the values of the WHEN statements fits. Here is an DECLARE @CharGender Char(1), @Gender Varchar(20); SET @CharGender = 'g'; SET @Gender = CASE @CharGender WHEN 'm' THEN 'Male' WHEN 'M' THEN 'Male' WHEN 'f' THEN 'Female' WHEN 'F' THEN 'Female' ELSE 'Unknown' END; SELECT 'Student Gender: ' + @Gender; GO This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If you don't produce an ELSE statement but a value not addressed by any of the WHEN statements is p would be NULL. Here is an example:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

This means that it is a valuable safeguard to always include an ELSE sub-statement in a CASE statement

WHILE

To examine a condition and evaluate it before taking action, you can use the WHILE operator. The b statement is: WHILE Expression Statement

When implementing this statement, first provide an Expression after the WHILE keyword. The Express true or a false result. If the Expression is true, then the interpreter executes the Statement. After execu the Expression is checked again. AS LONG AS the Expression is true, it will keep executing the Statement Expression becomes false, it stops executing the Statement. This scenario can be illustrated as follows:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Here is an example: DECLARE @Number As int WHILE @Number < 5 SELECT @Number AS Number GO

To effectively execute a while condition, you should make sure you provide a mechanism for the i referenced value for the condition, variable, or expression being checked. This is sometimes in the form initialized although it could be some other expression. Such a while condition could be illustrated as follow

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

This time, the statement would be implemented as follows: DECLARE @Number As int SET @Number = 1 WHILE @Number < 5 BEGIN SELECT @Number AS Number SET @Number = @Number + 1 END GO This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Boolean Constants
Introduction

Databases and other programming environments provide operators you can use to perform data anal used are called logical operators because they are used to perform comparisons that produce a result of is no middle result; in other words, something is not half true or half false or "Don't Know": either it is tru

The TRUE and FALSE Constants

In Boolean algebra, something is considered TRUE when it holds a value. The value is also consider contrast, if something doesn't hold a value, it is considered non-existent and non-worthy of consideratio ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

a value of FALSE, 0, or No. To retrieve such a value, you can just find out if the value of a field is existen

The comparison for a True or False value is mostly performed on Boolean fields, such a case is the SPHo whether a student lives in a single parent home) field of the Students table of the HighSchool database value of 1, the table considers that such a field is True. If the field has a 0 value, then it holds a FALSE v

The NULL Constant

After you have declared a variable, the SQL interpreter reserves a space in the computer memory for anything in that memory space. At that time, that area of memory doesn't hold a significant value. Als variable is considered null.

Here is note to be careful about: when a variable is said to hold a null value, it doesn't mean its value i mean that the variable's memory space is empty. It actually means that we cannot clearly determine the the variable is holding. To support the null value, Transact-SQL provides a constant named NULL. The NULL constant comparison purposes. For example, you can use an IF statement to check the nullity of a variable.

The IS Operator

To validate something as being possible, you can use the IS operator. For example, to acknowledge NULL, you can use the IS NULL expression. Here is an example: -- Square Calculation DECLARE @Side As Decimal(10,3), @Perimeter As Decimal(10,3), @Area As Decimal(10,3); SET @Perimeter = @Side * 4; SET @Area = @Side * @Side; IF @Side IS NULL PRINT 'A null value is not welcome' ELSE IF @Side > 0 BEGIN SELECT @Side AS Side; SELECT @Perimeter AS Perimeter ; SELECT @Area AS Area; END; ELSE PRINT 'You must provide a positive value'; GO This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

To avoid having a NULL value, you can either initialize the variable or you can assign it a value. Here is an -- Square Calculation DECLARE @Side As Decimal(10,3), @Perimeter As Decimal(10,3), @Area As Decimal(10,3); SET @Side = 48.126; SET @Perimeter = @Side * 4; SET @Area = @Side * @Side; IF @Side IS NULL PRINT 'A null value is not welcome' ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

ELSE IF @Side > 0 BEGIN SELECT @Side AS Side; SELECT @Perimeter AS Perimeter ; SELECT @Area AS Area; END; ELSE PRINT 'You must provide a positive value'; GO This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

The NOT Operator

To deny the presence, the availability, or the existence of a value, you can use the NOT operator. This o used to reverse a Boolean value. For example, we have learned that FALSE is the opposite of TRUE. TRUE is the opposite of FALSE. If you want to compare a value as not being TRUE, the NOT TRUE ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

same result as the FALSE value. For the same reason, the expression NOT FALSE is the same as TRUE.

Function Creation Fundamentals


There are various ways you can start the creating of a function: In the Object Explorer, expand the desired database. Expand the Programmatically node. Expand the Functions node. Right-click Scalar-Valued Function and click New Scalar-Valued Function... Sample code would be generated for you. You can then modify to customize it Open an empty query window. Display the Templates Explorer window and expand the Function node. Drag Create Scalar-Valued Function and drop it in the query window You can open a new empty query window and start typing your code in it

In Transact-SQL, the primary formula of creating a function is: CREATE FUNCTION FunctionName()

The Name of a Function

We mentioned already that, in SQL, a function is created as an object. As such, it must have a name here are the rules we will use to name our functions: A name will start with either an underscore or a letter. Examples are _n, act, or Second

After the first character as an underscore or a letter, the name will have combinations of underscore digits. Examples are _n24, act_52_t A name will not include special characters such as !, @, #, $, %, ^, &, or * We will avoid using spaces in a name, with few exceptions

If the name is a combination of words, each word will start in uppercase. Examples are DateHired, _ DriversLicenseNumber

Returning a Value From a Function

For a function to be useful, it must produce a result. This is also said that the function returns a result o creating a function, you must specify the type of value that the function would return. To provide this in the name of the function, type the RETURNS keyword followed by a definition for a data type. Here is a s CREATE FUNCTION Addition() RETURNS Decimal(6,3) ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

After specifying the type of value that the function would return, you can create a body for the function 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, yo assignment the function must perform. After performing this assignment, just before the END keyword, y the value that the function returns. This is done by typing the RETURN keyword followed by an expre 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

Practical Learning: Creating Functions


1. In the Object Explorer, right-click RealEstate1 and click New Query... 2. To create a function, type the following statement: CREATE FUNCTION CalculateWeeklySalary() RETURNS Decimal(8, 2) AS BEGIN RETURN 880.44 END; GO ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

3. To execute the statement, on the SQL Editor toolbar, click the Execute button 5. Type Calculate as the name of the file 6. Click Save

4. To save the file that contains the code of the function, on the Standard toolbar, click the Save button

7. In the Object Explorer, expand the RealEstate1 node, expand Programmability. Expand Functions. A Scalar-Valued Functions. Notice the presence of the CalculateWeeklySalary node

Function Calling

After a function has been created, you can use the value it returns. Using a function is also referred to call a function, you must qualify its name. To do this, type the name of the database in which it was crea the period operator, followed by dbo, followed by the period operator, followed by the name of the parentheses. The formula to use is: DatabaseName.dbo.FunctionName() Because a function returns a value, you can use that value as you see fit. For example, you can use SELECT to display the function's value in a query window. Here is an example that calls the above Additi PRINT Exercise.dbo.GetFullName();

As an alternative, to call a function, in the Object Explorer, right-click its name, position the mouse on Sc SELECT To, and click New Query Editor Window.

Practical Learning: Calling a Function


1. In the Object Explorer, right-click RealEstate1 and click New Query 2. To execute the function we just created, execute the following statement: PRINT RealEstate1.dbo.CalculateWeeklySalary(); GO

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

3. To specify a column name for the returned value of a function, change the function as follows and ex SELECT RealEstate1.dbo.CalculateWeeklySalary() AS [Weekly Salary]; GO

4. To save the current window, on the toolbar, click the Save button ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Function Maintenance
Introduction

Because a function in Transact-SQL is treated as an object, it may need maintenance. Some of the ac take include renaming, modifying, or deleting a function.

Renaming a Function

If you create a function and execute it, it is stored in the Scalar-Valued Functions node with the name yo want, you can change that name but keep the functionality of the function. To rename a function, in the Object Explorer, right-click it and click Rename. Type the desired new Enter.

Deleting a Function
If you create a function and decide that you don't need it any more, you can delete it.

To delete a function in the Object Explorer, locate the function in the Functions section, right-click it and Delete Object dialog box would come up. If you still want to delete the function, click OK; otherwise, click To programmatically delete a function:

In a query window, type DROP FUNCTION followed by the name of the function and execute the st

In the Object Explorer, right-click the name of the function, position the mouse on Script Function A click New Query Editor Window

Open a new query window associated with the database that contains the function. Display the Tem and expand the Function node. Drag the Drop Function node and drop it in the empty query window

Practical Learning: Deleting a Function

1. In the Object Explorer, under the Scalar-Valued Functions node, right-click dbo.CalculateWeeklySala Delete 2. In the Delete Object dialog box, click OK

Modifying a Function

As mentioned already, in the body of the function, you define what the function is supposed to tak minimum, a function can return a simple number, typed on the right side of the RETURN keyword. Here CREATE FUNCTION Addition() RETURNS int BEGIN RETURN 1 END

You can also declare new variables in the body of the function to help in carrying the assignment. A var the body of a function is referred to as a local variable. Once such a variable has been declared, it can other variable. Here is an example: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

CREATE FUNCTION Addition() RETURNS int BEGIN DECLARE @Number1 int SET @Number1 = 588 RETURN @Number1 + 1450 END

Practical Learning: Declaring Local Variables


1. In the Calculate query window, change the code as follows (notice the addition of the schema): CREATE FUNCTION Payroll.CalculateWeeklySalary() RETURNS Decimal(8, 2) AS BEGIN DECLARE @HourlySalary Decimal(8, 2), @WeeklyHours Real, @FullName varchar(100); SET @HourlySalary = 24.15; SET @WeeklyHours = 42.50; RETURN @HourlySalary * @WeeklyHours END; GO 2. Press F5 to execute the statement

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

3. To call the function, select and delete the code. Replace it with the following: SELECT RealEstate1.Payroll.CalculateWeeklySalary() AS [Weekly Salary]; GO 4. Execute the code by pressing F5

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Function Arguments
Introduction

In order to carry its assignment, a function can be provided with some values. Put it another way, wh function, instead of, or in addition to, local variables, you may want the code that will call the functio values needed to perform the assignment. For example, imagine you want to create a function that employees email addresses when a user has entered a first and last name. At the time you are creating t cannot know or predict the names of employees, including those who have not even been hired yet. In th write the whole function but provide one or more placeholders for values that would be supplied whe called.

An external value that is provided to a function is called a parameter. A function can also take more than Therefore, when you create a function, you also decide whether your function would take one or more what those parameters, if any, would be.

A Parameterized Function

We have already seen that a function's name is also followed by parentheses. If the function doesn't value, its parentheses can be left empty. If a function will use an external value, when you create the fu specify a name and the type of value of the parameters. The name of the parameter is created with th variable as we saw in the previous lesson. Here is an example: CREATE FUNCTION Addition(@Number1 Decimal(6,2)) ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

When a function takes a parameter, in the body of the function, you can use the parameter as if you kn long as you respect the type of that value. Here is an example: CREATE FUNCTION Addition(@Number1 Decimal(6,2)) RETURNS Decimal(6,2) BEGIN RETURN @Number1 + 1450 END

Calling a Parameterized Function

When you call a function that takes one parameter, you must supply a value for that argument. To d value of the parameter in the parentheses of the function. Here is an example:

A Function With Various Arguments

Instead of only one parameter, you can also create a function that takes more than one parameter. In th the arguments in the parentheses of the function with a comma. Here is an example: CREATE FUNCTION Addition(@Number1 Decimal(6,2), @Number2 Decimal(6,2))

Once again, in the body of the function, you can use the parameters as if you already knew their valu declare local variables and involve them with parameters as you see fit. Here is an example: CREATE FUNCTION Addition(@Number1 Decimal(6,2), @Number2 Decimal(6,2)) RETURNS Decimal(6,2) BEGIN ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

DECLARE @Result Decimal(6,2) SET @Result = @Number1 + @Number2 RETURN @Result END; GO When calling a function that takes more than one parameter, in the parentheses of the function, provide parameter, in the exact order they appear in the parentheses of the function. Here is an example: PRINT Variables1.dbo.Addition(1450, 228); You can also pass the names of already declared and initialized variables. Here is an example that function: DECLARE @Nbr1 Decimal(6,2), @Nbr2 Decimal(6,2) SET @Nbr1 = 4268.55 SET @Nbr2 =26.83 SELECT @Nbr1 As First, @Nbr2 As Second, Variables1.dbo.Addition(@Nbr1, @Nbr2) AS Result This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Practical Learning: Creating Functions With Arguments

1. In the Object Explorer, under the Scalar-Valued Functions node, right-click Payroll.CalculateWeeklyS Delete 2. In the Delete Object dialog box, click OK 3. To add arguments, change the code of the Calculate() function as follows: CREATE FUNCTION Payroll.CalculateWeeklySalary(@WeeklyHours Decimal(6,2), @HourlySalary SmallMoney) RETURNS Decimal(8, 2) AS BEGIN DECLARE @Weekly SmallMoney SELECT @Weekly = @WeeklyHours * @HourlySalary RETURN @Weekly END; GO 4. Press F5 to create the function 5. Delete the code in the window and replace it with the following: DECLARE @Hours Decimal(5,2), @Hourly SmallMoney SELECT @Hours = 42.50 SELECT @Hourly = 18.62 SELECT 'Hermine Singh' As [Employee Name], @Hours As [Weekly Hours], @Hourly As [Hourly Salary], RealEstate1.Payroll.CalculateWeeklySalary(@Hours, @Hourly) AS [Weekly Salary]; GO 6. Press F5 to execute the statement

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

7. Close the query window without saving the file 8. In the Object Explorer, under the Databases node, right-click RealEstate1 and click Delete 9. In the dialog box, click OK

Creating a Primary Key With SQL


To create a primary column using SQL, the primary thing to do is, on the right side of the column definition, type PRIMARY KEY. Here is an example: CREATE TABLE Persons ( PersonID int identity(1,1) PRIMARY KEY NOT NULL, FirstName varchar(20), LastName varchar(20) NOT NULL ); ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

The Primary Key Constraint


In the SQL, you can give a specific name to a primary key. To do this, you can first create the column. Then, somewhere before the closing parenthesis of the table, specify the primary key column using the following formula: CONSTRAINT PrimaryKeyName PRIMARY KEY(ColumnName) In this formula, the CONSTRAINT keyword and the PRIMARY KEY (case-insensitive) expression are required. In the PrimaryKeyName placeholder, enter the name you want to give to the primary key. In the parentheses of the PRIMARY KEY expression, enter the name of the column that will be used as the primary key. Here is an example: CREATE TABLE Persons ( PersonID int identity(1,1) NOT NULL, FirstName varchar(20), LastName varchar(20) NOT NULL, CONSTRAINT PrimKeyPeople PRIMARY KEY(PersonID) ); By convention or tradition, the name of the primary starts with PK_ followed by the name of the table. Here is an example: USE Exercise2; GO CREATE TABLE Persons ( PersonID int identity(1,1) NOT NULL, FirstName varchar(20), LastName varchar(20) NOT NULL, CONSTRAINT PK_Persons PRIMARY KEY(PersonID) ); GO

The Foreign Key


Introduction
Continuing with our bank database, imagine a customer comes to the bank to deposit money. We already established that it would be redundant to create a new account every time the customer comes to perform a transaction. Instead, you would get the customer's information from his or her account, provide that information to the table used to process transactions. As we described earlier, the account table should be able to provide its data to the other tables that would need that data. To make this flow of information possible from one table to another, you must create a relationship between them.

Creating a Foreign Key in the Table Design View


To make it possible for a table B to receive data from a table A, the table B must have a column that represents the table A. This columns acts as an "ambassador" or a link. As a ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

pseudo-ambassador, the column in the table B almost doesn't belong to that table: it primarily allows both tables to communicate. For this reason, the column in the table B is called a foreign key. A foreign key is a column on a table whose data is coming from another table. To create a foreign key in the Table Design window, in the table that will receive the key, simply create a column with the following rules: The column should have the same name as the primary column of the table it represents (but this is not a requirement) The column must (this is required) have the same data type as the primary column of the table it represents

Here is an example of a column named GenderID that is a foreign key:

Obviously in order to have information flowing from one table to another, the table that holds the primary information must be created. You can create it before or after creating the other table, as long as you haven't established any link between both tables, it doesn't matter what sequence you use to create them. The table that contains a primary key and that holds the information that another table would use is called the primary table or the parent table. The table that will receive the information from the other table is called the foreign table or the child table.

Creating a Foreign Key in the Relationships Dialog Box


To create a foreign key in a table: 1. From the Object Explorer, open the child table in Design View

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

2. Right-click anywhere in the table and click Relationships...

3. In the Foreign Key Relationships dialog box, click Add 4. A default name would be suggested to you. You can accept or change it. To change the name of the foreign key, in the right side, expand Identity and edit the string in the (Name) field:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

5. If necessary, in the same way, you can create other foreign keys by clicking Add. To delete an existing foreign key, first select it under Selected Relationships and click Delete. Once you are ready, click Close

Creating a Foreign Key in SQL


You can also create a foreign key in the SQL. The basic formula to use is: FOREIGN KEY REFERENCES ParentTableName(ForeignKeyCcolumn) The FOREIGN KEY expression and the REFERENCES keyword are required. In the ParentTableName placeholder, enter the name of the primary table that holds the information that will be accessed in the current table. In the parentheses of ParentTableName, enter the name of the primary column of the parent table. Here is an example: CREATE TABLE Persons ( PersonID int identity(1,1) PRIMARY KEY NOT NULL, FirstName varchar(20), LastName varchar(20) NOT NULL, GenderID int NULL FOREIGN KEY REFERENCES Genders(GenderID) );

The Foreign Key Constraint


ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Notice that the foreign key doesn't have an object name as we saw for the primary key. If you don't specify a name for the foreign key, the SQL interpreter would automatically create a default name for you. Otherwise, to create a name, after creating the column, enter the CONSTRAINT keyword followed by the desired name and continue the rest as we saw above. Her is an example: CREATE TABLE Persons ( PersonID int identity(1,1) PRIMARY KEY NOT NULL, FirstName varchar(20), LastName varchar(20) NOT NULL, GenderID int NULL CONSTRAINT FKGenders FOREIGN KEY REFERENCES Genders(GenderID) );

Establishing a Relationship
Introduction
As mentioned already, a relational database is one in which information flows from one table to another. To prepare the tables for this, you create primary and foreign keys, which we have done so far. Once the tables are ready, you can link them, which is referred to as creating a relationship between two tables. If you didn't create a foreign key with SQL code, you can create it when establishing a relationship between two tables.

Creating a Relationship
To create a relationship between two tables 1. Open the child table in the design view 2. Right-click (anywhere in) the table and click Relationships... If the (necessary) foreign key doesn't exist, click Add and specify its name under Identity) in the right side. 3. Under Selected Relationships, click the foreign key that will hold the relationship 4. In the right side, expand Tables And Columns Specification 5. Click its ellipsis button 6. In the Primary Key Table combo box, select the parent table that holds the primary data 7. Under the parent table, click and select its primary key column 8. Under Foreign Key Table, make sure the name of the current table is set. Under the name of the child table, click and select the name of the foreign key column. Here is an example:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

9. Click OK. When a relationship has been created, it would show in the Tables And Column Specification section:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

10. In the same way, you can create other relationships by clicking Add and configuring the link. Once you have finished, click Close

Practical Learning: Creating Relationships


1. To complete our database with its tables, their primary keys, their foreign keys, and some data in the tables, change the code in the query window as follows: -- ============================================= -- Database: YugoNationalBank -- Author: FunctionX -- Date Created: Monday 09 April 2007 -- ============================================= USE master GO -- Drop the database if it already exists IF EXISTS ( SELECT name FROM sys.databases WHERE name = N'YugoNationalBank' ) DROP DATABASE YugoNationalBank GO CREATE DATABASE YugoNationalBank GO -- ========================================= -- Database: YugoNationalBank -- Table: Locations -- ========================================= USE YugoNationalBank GO IF OBJECT_ID('dbo.Locations', 'U') IS NOT NULL DROP TABLE dbo.Locations GO CREATE TABLE Locations ( LocationID int Identity(1,1) NOT NULL, LocationCode varchar(10) NOT NULL, Address varchar(120), City varchar(50), State varchar(50), Notes text NULL, CONSTRAINT PK_Locations PRIMARY KEY (LocationID) ); GO -- ========================================= -- Database: YugoNationalBank ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

-- Table: AccountTypes -- ========================================= USE YugoNationalBank GO IF OBJECT_ID('dbo.AccountTypes', 'U') IS NOT NULL DROP TABLE dbo.AccountTypes GO CREATE TABLE AccountTypes ( AccountTypeID int Identity(1,1) NOT NULL, AccountType varchar(40) NOT NULL, Notes text NULL, CONSTRAINT PK_AccountTypes PRIMARY KEY (AccountTypeID) ); GO ----IF ========================================= Database: YugoNationalBank Table: Employees ========================================= OBJECT_ID('dbo.Employees', 'U') IS NOT NULL DROP TABLE dbo.Employees

GO CREATE TABLE Employees ( EmployeeID int identity(1,1) NOT NULL, EmployeeNumber char(6), FirstName varchar(32), LastName varchar(32) NOT NULL, Title varchar(50), CanCreateNewAccount bit, HourlySalary smallmoney, EmailAddress varchar(100), Username varchar(20), Password varchar(20), Notes text, CONSTRAINT PK_Employees PRIMARY KEY (EmployeeID) ); GO ----IF ========================================= Database: YugoNationalBank Table: Customers ========================================= OBJECT_ID('dbo.Customers', 'U') IS NOT NULL DROP TABLE dbo.Customers

GO CREATE TABLE Customers ( CustomerID int Identity(1,1) NOT NULL, ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

DateCreated datetime, AccountNumber varchar(20), AccountTypeID int Constraint FK_TypeOfAccount References AccountTypes(AccountTypeID), CustomerName varchar(50) NOT NULL, DateUpdated smallDateTime, Notes text, CONSTRAINT PK_Customers PRIMARY KEY (CustomerID) ); GO ----IF GO ----IF GO CREATE TABLE Deposits ( DepositID int identity(1, 1) NOT NULL, LocationID int Constraint FK_DepositLocation References Locations(LocationID) NOT NULL, EmployeeID int Constraint FK_Clerk References Employees(EmployeeID), CustomerID int Constraint FK_Depositor References Customers(CustomerID) NOT NULL, DepositDate smalldatetime NOT NULL, DepositAmount smallmoney NOT NULL, Notes text, CONSTRAINT PK_Deposits PRIMARY KEY (DepositID) ); GO ----IF GO CREATE TABLE Withdrawals ( ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com ========================================= Database: YugoNationalBank Table: Withdrawals ========================================= OBJECT_ID('dbo.Withdrawals', 'U') IS NOT NULL DROP TABLE dbo.Withdrawals ========================================= Database: YugoNationalBank Table: ChargeReasons ========================================= OBJECT_ID('dbo.ChargeReasons', 'U') IS NOT NULL DROP TABLE dbo.ChargeReasons ========================================= Database: YugoNationalBank Table: Deposits ========================================= OBJECT_ID('dbo.Deposits', 'U') IS NOT NULL DROP TABLE dbo.Deposits

WithdrawalID int identity(1, 1) NOT NULL, LocationID int Constraint FK_WithdrawlLocation References Locations(LocationID) NOT NULL, EmployeeID int Constraint FK_ProcessedBy References Employees(EmployeeID), CustomerID int Constraint FK_CustomerAccount References Customers(CustomerID) NOT NULL, WithdrawalDate smalldatetime NOT NULL, WithdrawalAmount smallmoney NOT NULL, WithdrawalSuccessful bit NOT NULL, Notes text, CONSTRAINT PK_Withdrawas PRIMARY KEY (WithdrawalID) ); ----IF GO CREATE TABLE CheckCashing ( CheckCashingID int identity(1, 1) NOT NULL, LocationID int Constraint FK_BranchLocations References Locations(LocationID) NOT NULL, EmployeeID int Constraint FK_Employees References Employees(EmployeeID), CustomerID int Constraint FK_Customers References Customers(CustomerID) NOT NULL, CheckCashingDate smalldatetime NOT NULL, CheckCashingAmount smallmoney NOT NULL, CheckCashingSuccessful bit NOT NULL, Notes text, CONSTRAINT PK_CheckCashing PRIMARY KEY(CheckCashingID) ); GO 2. Press F5 to execute the statement ========================================= Database: YugoNationalBank Table: CheckCashing ========================================= OBJECT_ID('dbo.CheckCashing', 'U') IS NOT NULL DROP TABLE dbo.CheckCashing

Diagrams
A diagram is a window that visually displays the relationships among tables of a database. To create a diagram: 1. In the Object Explorer, in the database node, you can click Database Diagrams 2. A dialog box will inform you that this database doesn't have a diagram. Read the message and click Yes 3. Right-click Database Diagrams and click New Database Diagram ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

4. In the Add Table dialog box, click each table and click the Add. Alternatively, you can double-click a table to add it 5. In the Add Table dialog box, you can click Close. On the toolbar, you can click the Zoom button and select a larger or smaller value. To move a table, you can drag its title bar. Here is an example:

6. To establish a relationship, you can click the gray box on the left of any column from the parent table and drop it on any column in the child table. A better way is to click gray box of the primary key column from the parent table, drag that box then drop it on the foreign key column of the child table. Here is an example:

7. A Tables and Columns dialog box would come up. It would display the column that was dragged and the column on which you dropped. If you had selected just any column, it would show but it may not be the one you wanted to drag; that is, it may not be the actual column that is supposed to manage the relationship. Regardless, under Primary Key Table, you should select the parent table 8. Under the parent table, select its primary column

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

9. Under Foreign Table, select the foreign key column. Here is an example:

10. Once you are ready, click OK. A link would be created between the tables

11. In the same way, you can create other relationships. When you have finished, you can save and close the database

Practical Learning: Creating a Diagram


1. In the Object Explorer, in the YugoNationalBank node, click Database Diagrams 2. A dialog box will inform you that this database doesn't have a diagram:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Read the message and click Yes 3. Right-click Database Diagrams and click New Database Diagram 4. In the Add Table dialog box, click Customers and click the Add > button 5. Double-click CheckCashing to add it 6. In the same way, add the AccountTypes , Deposits, Employees, Locations, and Withdrawals tables 7. On the Add Table dialog box, click Close. Notice that, based on how we created the database and its objects, the relationships have been created already:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

8. To save the diagram, on the Standard toolbar, click Save 9. Set its name to dgmYugoNationalBank and click OK 10. Close the window

Referential Integrity
On a typical database, information comes and goes. For a bank, customers accounts are created and deleted on a regular basis. When an account is deleted, there is concern about the transactions related to that account. Referential integrity allows you to manage ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

these aspects of a database. You need to make sure that when data is deleted from a parent table, the child tables are notified and their related records are deleted also. When information is changed on a parent table, the related information is changed in the child tables. To manage referential integrity, you use the Foreign Key Relationships dialog box. You can access it from the design view of a table or from the diagram window.

Practical Learning: Managing Referential Integrity


1. In the Object Explorer, expand the Tables node under YugoNationalBank. Right-click dbo.Customers and click Design 2. Right-click in the table and click Relationships 3. Under Selected Relationships, click FK_CustomerAccount. In the right section, expand INSERT And UPDATE Specification 4. Click Delete Rule. In its combo box, select Cascade 5. Click Update Rule. In its combo box, select Cascade:

6. In the same way, specify the following Delete Rule Cascade

Foreign Key FK_ChargeReasons

Update Rule Cascade

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

FK_Customers FK_Depositor FK_TypeOfAccount 7. Click Close

Cascade Cascade Cascade

Cascade Cascade Cascade

8. Save and close the table 9. In the same way, open the Deposits table in design view 10. Access its Relationships dialog box 11. Access the properties of its FK_Clerk field. Specify its Delete Rule and its Update Rule both to Cascade 12. Perform the same actions for the other relationships 13. Close the Relationships dialog box 14. Save and close the table

SELECT WhatColumn(s) FROM ChildTable TypeOfJoin ParentTable ON Condition The ChildTable factor specifies the table that holds the records that will be retrieved. It can be represented as follows: SELECT WhatColumn(s) FROM Persons TypeOfJoin ParentTable ON Condition

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

The ParentTable factor specifies the table that holds the column with the primary key that will control what records, related to the child table, that will display. This factor would be represented as follows: SELECT WhatColumn(s) FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID The Condition factor is a logical expression used to validate the records that will be isolated. To create the condition, you should assign the primary key column of the parent table to the foreign key column of the child table. Because both columns likely have the same name, to distinguish them, their names should be qualified. This would be done as follows: SELECT WhatColumn(s) FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID The WhatColumn(s) factor of our formula allows you to make a list of the columns you want to include in your statement. As you should be aware, you can include all columns by using the * operator. Here is an example: SELECT * FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID In this case, all columns from all tables would be included in the result. Instead of all columns, you may want a restricted list. In this case, create the list after the SELECT keyword separating them with commas. You can use the name of a column normally if that name is not duplicated in more than one column. Here is an example: SELECT LastName, FirstName, Gender FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID If the same name of a column is found in more than one table, as is the case for a primary-foreign key combination, you should qualify the name. Here is an example: SELECT LastName, FirstName, Persons.GenderID, Genders.GenderID, Gender FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID In fact, to make your code easier to read, you should qualify the name of each column of your SELECT statement. Here is an example: SELECT Persons.LastName, Persons.FirstName, Persons.GenderID, Genders.GenderID, Genders.Gender ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID

Practical Learning: Preparing a Join


1. In the Object Explorer, right-click Databases and click Refresh 2. Expand Databases and expand RealEstate2 3. Expand its Tables node 4. Right-click the Properties table and click Open Table 5. On the Query Designer toolbar, click the Show Diagram Pane button Show SQL Pane button 6. On the Query Design toolbar, click the Add Table button 7. In the Add Table dialog box, double-click PropertyTypes 8. Click Close and the

Cross and Inner Joins


Introduction
When studying data relationships, we saw the role of the primary and foreign keys in maintaining the exchange of information between two tables. This technique of linking tables plays a major part when creating a join. It allows you to decide whether you want to include all records or only isolate some of them. To respect the direction of a relationship between two tables as it is applied to a query, Transact-SQL supports three types of joins.

Cross Joins
A cross join creates a list of all records from both tables as follows: the first record from the parent table is associated to each record from the child table, then the second record from the parent table is associated to each record from the child table, and so on. In this case also, there is no need of a common column between both tables. In other words, you will not use the ON clause. To create a cross join, you can replace the TypeOfJoin factor of our formula with CROSS JOIN or CROSS OUTER JOIN. Here is an example: SELECT Persons.PersonID, Persons.FirstName, Persons.LastName, Genders.GenderID, Genders.Gender FROM Persons CROSS JOIN Genders GO

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

By default, from the SQL Server Management Studio, after you have just added a table to another one (if no relationship was already established between both tables), the query would be automatically made a cross join. All you have to do is to select the needed columns. After selecting the columns, you can execute the query to see the result:

Inner Joins
Imagine you have two tables that can be linked through one's primary key and another's foreign key.

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Notice that some records in the Persons table don't have an entry for the GenderID column and were marked with NULL by the database engine. When creating a query of records of the Persons table, if you want your list to include only records that have an entry, you can create it as inner join. By default, from the SQL Server Management Studio, when creating a new query, if a relationship was already established between both tables, the query is made an inner join. If there was no relationship explicitly established between both tables, you would have to create it edit the SQL statement. Consider the following:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Notice that, because no relationship was previously established between both tables, the join is crossed. To create an inner join, you have two options. You can drag the primary key from the parent table and drop it on the foreign key in the child table. Here is an example:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Alternatively, you can edit the SQL statement manually to make it an inner join. To do this, you would specify the TypeOfJoin factor of our formula with the expression INNER JOIN. Here is an example: SELECT Persons.PersonID, Persons.FirstName, Persons.LastName, Persons.GenderID, Genders.GenderID AS [Gender ID], Genders.Gender FROM Persons INNER JOIN Genders ON Persons.GenderID = Genders.GenderID After creating the join, in the Diagram section, a line would be created to join the tables. You can then execute the query to see the result. This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

We mentioned earlier that you could include all columns in the query. In our result, since we are more interested in the gender of each Persons record, we would not need the GenderID column from the Genders table. Here is an example:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

As mentioned earlier, notice that the result includes only records that have an entry (a non-NULL entry) in the GenderID foreign key column of the Persons table. An alternative to the INNER JOIN expression is to simply type JOIN. Here is an example: SELECT Persons.PersonID, Persons.FirstName, Persons.LastName, Genders.Gender FROM Persons JOIN Genders ON Persons.GenderID = Genders.GenderID GO To destroy a join between two tables, if you are working in the Table window, you can right-click the line that joins the tables and click Remove. In SQL, you must modify the expressions that make up the join (the JOIN and the ON expressions).

Practical Learning: Creating an Inner Join


ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

1. To create an inner join, from the PropertyTypes table, drag PropertyTypeID and drop it on the PropertyTypeID field of the Properties table:

2. Release the mouse 3. On the tables, select the following fields: PropertyType, City, Bedrooms, Bathrooms, YearBuilt, and MarketValue

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

4. On the Query Designer toolbar, click the Execute button to see the result

Outer Joins
ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Introduction
Instead of showing only records that have entries in the child table, you may want your query to include all records, including those that are null. To get this result, you would create an outer join. You have three options.

Left Outer Joins


A left outer join produces all records of the child table, also called the right table. The records of the child table that don't have an entry in the foreign key column are marked as NULL. To create a left outer join, if you are working in the Table window, in the Diagram section, right-click the line that joins the tables and click the option that would select all records from the child table (in this case, that would be Select All Rows From Persons):

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Alternatively, you can replace the TypeOfJoin factor of our formula with either LEFT JOIN or LEFT OUTER JOIN. Here is an example: SELECT Persons.PersonID, Persons.FirstName, Persons.LastName, Genders.GenderID, Genders.Gender FROM Persons LEFT OUTER JOIN Genders ON Persons.GenderID = Genders.GenderID GO

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

In both cases, the button in the middle of the line would be added an arrow that points to the parent table. You can then execute the query to see the result. Here is an example:

Notice that the result includes all records of the Persons (also called the right) table and the records that don't have an entry in the GenderID column of the Persons (the right) table are marked with NULL.

Right Outer Joins


A right outer join considers all records from the parent table and finds a matching record in the child table. To do this, it starts with the first record of the parent table (in this case the Genders table) and shows each record of the child table (in this case the Persons table) that has a corresponding entry. This means that, in our example, a right outer join would first create a list of the Persons records that have a 1 (Female) value for the GenderID column. After the first record, the right outer join moves to the second record, and so on, each time listing the records of the child table that have a corresponding entry for the primary key of the parent table. ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

To visually create a right outer join in the Table window, after establishing a join between both tables, if you had previously created a left outer join, you should remove it by rightclicking the line between the tables and selecting the second option under Remove. Then, you can right-click the line that joins them and click the option that would select all records from the parent table. In our example, you would click Select All Rows From Genders. To create a right outer join in SQL, you can replace the TypeOfJoin factor of our formula with RIGHT JOIN or RIGHT OUTER JOIN. Here is an example: SELECT Persons.PersonID, Persons.FirstName, Persons.LastName, Genders.GenderID, Genders.Gender FROM Persons RIGHT OUTER JOIN Genders ON Persons.GenderID = Genders.GenderID GO In both cases, the button on the joining line between the tables would have an arrow that points to the child table. You can then run the query. Here is an example:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Notice that the query result starts with the first record of the parent table, also called the left table (in this case the Genders table), and lists the records of the child table, also called the right table (in this case the Persons table), that have the entry corresponding to that first record. Then it moves to the next GenderID value. Also, notice that there are no NULL records in the Gender.

Practical Learning: Getting Non-NULL Records


1. To get a list of only properties whose types are known, right-click the line between the tables and click Select all rows from PropertyTypes 2. On the Query Designer toolbar, click the Execute button

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

3. Notice that the result is the list of tables in order by types (condos, single families, and town homes)

Full Outer Joins


A full outer join produces all records from both the parent and the child tables. If a record from one table doesn't have a value in the other value, the value of that record is marked as NULL. To visually create a full outer join, in the Table window, right-click the line between the tables and select each option under Remove so that both would be checked. To create a full outer join in SQL, replace the TypeOfJoin factor of our formula with FULL JOIN or FULL OUTER JOIN. Here is an example: SELECT Persons.PersonID, Persons.FirstName, Persons.LastName, Genders.GenderID, Genders.Gender FROM Persons FULL OUTER JOIN Genders ON Persons.GenderID = Genders.GenderID GO The button on the line between the tables would now appear as a square. You can then execute the query. Here is an example:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Just as we have involved only two tables in our joins so far, you can create a join that includes many tables.

Joins and Data Analysis


Introduction
As demonstrated so far and in previous lessons, the main reason for creating queries is to isolate records. This is done using conditions and criteria. Joins enhance this capability because they allow you to consider records from different tables and include them in a common SQL statement. In the joins we have created so far, we considered all records and let the database engine list them using only the rules of joins built-in the SQL. To make such a list more useful or ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

restrictive, you can pose your own conditions that should be respected to isolate records like a funnel. As done in previous lessons, to include a criterion in a SELECT statement, you can create a WHERE clause.

Using Criteria
To create a criterion in a query you create from the SQL Server Management Studio, first select a column to display it in the Grid section. Just as reviewed in the previous lessons when creating a query, to specify a criterion, in the Criteria box corresponding to the column, type the condition using any of the operators we reviewed in previous lessons. Here is an example: SELECT Persons.PersonID, Persons.FirstName, Persons.LastName, Genders.GenderID, Genders.Gender FROM Persons LEFT OUTER JOIN Genders ON Persons.GenderID = Genders.GenderID WHERE Genders.Gender = 'female') This would produce:

CREATE FUNCTION dbo.GetFullName ( @FName varchar(20), @LName varchar(20) ) RETURNS varchar(41) AS BEGIN RETURN @LName + ', ' + @FName; END GO Once you have a function you want to use, you can call it in the body of your view as you judge it necessary. Here is an example: CREATE VIEW dbo.MyPeople AS SELECT dbo.GetFullName(FirstName, LastName) AS [Full Name], dbo.Genders.Gender FROM Genders INNER JOIN dbo.Persons ON dbo.Genders.GenderID = dbo.Persons.GenderID; This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Practical Learning: Introducing Stored Procedures


1. Start Microsoft SQL Server Management Studio and log in to your server 2. On the main menu, click File -> New -> Query With Current Connection 3. To create a new database, enter the following code in the window -- ============================================= -- Database: WattsALoan -- ============================================= USE master GO -- Drop the database if it already exists IF EXISTS ( SELECT name FROM sys.databases WHERE name = N'WattsALoan' ) DROP DATABASE WattsALoan GO CREATE DATABASE WattsALoan GO -- ========================================= -- Table: Employees -- ========================================= USE WattsALoan GO IF OBJECT_ID('dbo.Employees', 'U') IS NOT NULL DROP TABLE dbo.Employees GO CREATE TABLE dbo.Employees ( EmployeeID int identity(1,1) NOT NULL, EmployeeNumber nchar(10) NULL, FirstName varchar(20) NULL, LastName varchar(10), FullName AS ((LastName+ ', ') + FirstName), Title varchar(100), HourlySalary money, Username varchar(20), Password varchar(20), CONSTRAINT PK_Employees PRIMARY KEY(EmployeeID) ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

) GO INSERT INTO dbo.Employees(EmployeeNumber, FirstName, LastName, Title, HourlySalary) VALUES('293747', 'Jeanne', 'Tryler', 'Accounts Manager', 22.24); GO INSERT INTO dbo.Employees(EmployeeNumber, FirstName, LastName, Title, HourlySalary) VALUES('492947', 'Helene', 'Gustman', 'Accounts Representative', 14.55); GO INSERT INTO dbo.Employees(EmployeeNumber, FirstName, LastName, Title, HourlySalary) VALUES('804685', 'Ernest', 'Thomas', 'Accounts Representative', 12.75); GO -- ========================================= -- Table: LoanTypes -- ========================================= USE WattsALoan GO IF OBJECT_ID('dbo.LoanTypes', 'U') IS NOT NULL DROP TABLE dbo.LoanTypes GO CREATE TABLE dbo.LoanTypes ( LoanTypeID int identity(1,1) NOT NULL, LoanType varchar(50) NOT NULL, CONSTRAINT PK_LoanTypes PRIMARY KEY(LoanTypeID) ); GO INSERT INTO LoanTypes(LoanType) VALUES('Personal Loan'); GO INSERT INTO LoanTypes(LoanType) VALUES('Car Financing'); GO INSERT INTO LoanTypes(LoanType) VALUES('Credit Card'); GO INSERT INTO LoanTypes(LoanType) VALUES('Furniture Loan'); GO -- ========================================= -- Table: Customers -- ========================================= USE WattsALoan GO IF OBJECT_ID('dbo.Customers', 'U') IS NOT NULL DROP TABLE dbo.Customers GO CREATE TABLE dbo.Customers ( ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

CustomerID int identity(1,1) NOT NULL, DateCreated datetime NULL, FullName varchar(50) NOT NULL, BillingAddress varchar(100), BillingCity varchar(50), BillingState varchar(50), BillingZIPCide varchar(10), EmailAddress varchar(100), CONSTRAINT PK_Customers PRIMARY KEY(CustomerID) ) GO INSERT INTO Customers(DateCreated, FullName, BillingAddress, BillingCity, BillingState, BillingZIPCide, EmailAddress) VALUES('2/26/2004', 'Julius Ramse', '927 Feuler Ave', 'Silver Spring', 'MD', '20904', 'ramses1990@netscape.net'); GO INSERT INTO Customers(DateCreated, FullName, BillingAddress, BillingCity, BillingState, BillingZIPCide) VALUES('06/22/2006', 'Gertrude Vaillant', '10055 Larsenic Rd', 'Takoma Park', 'MD', '20910'); GO INSERT INTO Customers(DateCreated, FullName, BillingAddress, BillingCity, BillingState, BillingZIPCide, EmailAddress) VALUES('12/3/2004', 'James Barrouch', '4204 Fallon Drive', 'Silver Spring', 'MD', '20906', 'barrouchj@hotmail.com'); GO INSERT INTO Customers(DateCreated, FullName, BillingAddress, BillingCity, BillingState, BillingZIPCide) VALUES('08/02/2006', 'Christine Rougher', '825 Manning Street', 'Alexandria', 'VA', '22231'); GO INSERT INTO Customers(DateCreated, FullName, BillingAddress, BillingCity, BillingState, BillingZIPCide, EmailAddress) VALUES('10/08/2006', 'Patrick Heller', '2480 Clarington Drive NW', 'Washington', 'DC', '20006', 'hellerp@yahooo.com'); GO -- ========================================= -- Table: LoanAllocation -- ========================================= USE WattsALoan GO ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

IF OBJECT_ID('dbo.LoanAllocations', 'U') IS NOT NULL DROP TABLE dbo.LoanAllocations GO CREATE TABLE dbo.LoanAllocations ( LoanAllocationID int identity(1,1) NOT NULL, DatePrepared datetime NOT NULL, EmployeeID int NULL CONSTRAINT FK_LoanPreparer FOREIGN KEY REFERENCES Employees(EmployeeID), CustomerID int NOT NULL CONSTRAINT FK_LoanReceiver FOREIGN KEY REFERENCES Customers(CustomerID), AccountNumber char(10), LoanTypeID int NOT NULL CONSTRAINT FK_LoanTypes FOREIGN KEY REFERENCES LoanTypes(LoanTypeID), LoanAmount money NOT NULL, InterestRate decimal(6,2) NOT NULL, Periods decimal(6,2) NOT NULL, InterestAmount AS ((LoanAmount*(InterestRate/(100)))*(Periods/(12))), FutureValue AS (LoanAmount+(LoanAmount*(InterestRate/(100)))*(Periods/(12))), MonthlyPayment AS ((LoanAmount+(LoanAmount*(InterestRate/(100)))*(Periods/(12)))/Periods) , Notes Text, CONSTRAINT PK_LoanAllocations PRIMARY KEY(LoanAllocationID) ) GO INSERT INTO LoanAllocations(DatePrepared, EmployeeID, CustomerID, AccountNumber, LoanTypeID, LoanAmount, InterestRate, Periods, Notes) VALUES('2/26/2004', 2, 1, '9171394', 4, 6500.00, 12.65, 36, 'The loan will be delivered by our furniture business partner Helios Furnian'); GO INSERT INTO LoanAllocations(DatePrepared, EmployeeID, CustomerID, AccountNumber, LoanTypeID, LoanAmount, InterestRate, Periods, Notes) VALUES('06/22/2007', 2, 2, '8628064', 2, 16500.00, 10.20, 60, 'For this car loan, our partner Arlington Honda will process and deliver the car.'); GO INSERT INTO LoanAllocations(DatePrepared, EmployeeID, CustomerID, AccountNumber, LoanTypeID, LoanAmount, InterestRate, Periods, Notes) VALUES('12/3/2006', 1, 3, '8468364', 3, 500.00, 18.65, 48, 'This is a regular credit card.'); GO ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

INSERT INTO LoanAllocations(DatePrepared, EmployeeID, CustomerID, AccountNumber, LoanTypeID, LoanAmount, InterestRate, Periods, Notes) VALUES('08/02/2006', 3, 4, '2483047', 1, 3500.00, 12.74, 36, 'This is personal/cash loan allocated to a customer who walked in the store and requested it.'); GO INSERT INTO LoanAllocations(DatePrepared, EmployeeID, CustomerID, AccountNumber, LoanTypeID, LoanAmount, InterestRate, Periods, Notes) VALUES('10/08/2006', 2, 5, '1311804', 4, 22748.36, 12.28, 60, 'This is a regular car financing loan'); GO -- ========================================= -- Table: Payments -- ========================================= USE WattsALoan GO IF OBJECT_ID('dbo.Payments', 'U') IS NOT NULL DROP TABLE dbo.Payments GO CREATE TABLE dbo.Payments ( PaymentID int identity(1, 1) NOT NULL, PaymentDate datetime NOT NULL, EmployeeID int NULL CONSTRAINT FK_Employees FOREIGN KEY REFERENCES Employees(EmployeeID), LoanAllocationID int NOT NULL CONSTRAINT FK_LoanAllocations FOREIGN KEY REFERENCES LoanAllocations(LoanAllocationID), PaymentAmount money NOT NULL, Balance money, Notes Text, CONSTRAINT PK_Payments PRIMARY KEY(PaymentID) ) GO 4. To execute the code, press F5 5. In the Object Explorer, expand the Databases node if necessary and expand WattsALoan 6. Click Database Diagram 7. When the message box comes up, read it and click Yes 8. Right-click Database Diagram and click New Database Diagram... 9. In the dialog box, double-click each table and, when all tables have been added, click Close ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

10. Save the diagram as dgmWattsALoan and close it

Creating a Stored Procedure


To create a procedure:

In the Object Explorer, expand the database for which you want to create the procedure, expand its Programmability node, right-click Stored Procedures, and click New Stored Procedure... A query win skeleton syntax would be displayed. You can then modify that code using the techniques we will lear Open an empty query window associated with the database for which you want to create the stored display the Templates Explorer. In the Templates Explorer, expand the Store Procedure node. Drag Procedure and drop it in the query window Open an empty query window associated with the database for which you want to create the stored enter the necessary code

In SQL, to create a procedure, you start with the CREATE PROCEDURE expression. You can also use Both expressions produce the same result. Like everything in your database, you must name your proced

The name of a procedure can be any string that follows the rules we reviewed for naming the func

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Refrain from starting the name of a procedure with sp_ because it could conflict with some of the st that already ship with Microsoft SQL Server.

After the name of the procedure, type the keyword AS. The section, group of words, or group of lin keyword is called the body of the procedure. It states what you want the procedure to do or what you wa Based on this, the simplest syntax of creating a procedure is: CREATE PROCEDURE ProcedureName AS Body of the Procedure It is important to keep in mind that there are many other issues related to creating a procedure but consider that syntax.

After creating the procedure, you must store it as an object in your database. To do this, on the SQL Ed

can click the Execute button . If the code of the procedure is right, it would be created and a new n would be added to the Stored Procedures section of the database.

Managing Procedures
Modifying a Procedure
As a regular SQL Server database object, you can modify a stored procedure without recreating it. To do In the Object Explorer, you can right-click the procedure and click Modify

In the Object Explorer, you can right-click the procedure, position the mouse on Script Stored Proce ALTER To -> New Query Editor Window

Open an empty query window associated with the database that contains the stored procedure. From Explorer, expand Stored Procedure. Drag the Drop Stored Procedure node and drop it in the empty q

In each case, a skeleton code would be generated for you. You can then edit it to create a new versio procedure. After editing the code, you can execute the SQL statement to update the stored procedure. In SQL, the basic formula to modify a stored procedure is: ALTER PROCEDURE ProcedureName AS Body of Procedure

Deleting a Procedure

One of the biggest characteristics of a stored procedure is that it is treated like an object in its own right. creating it, if you don't need it anymore, you can get rid of it.

There are various types of stored procedures, some of which are considered temporary. Those types of p themselves when not needed anymore, such as when the person who created the stored procedure disco database or shuts down the computer. Otherwise, to delete a procedure, you can use either the Object As mentioned with tables, even if you create a procedure using the Object Explorer, you can delete it usin versa. ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

To remove a procedure in the Object Explorer, after expanding its database, its Programmability, Procedure nodes, you can right-click the stored procedure and click Delete. You can also click it in the O select it and then press Delete. The Delete Object dialog box would come up to let you make a decision. To delete a procedure in SQL, the syntax to use is: DROP PROCEDURE ProcedureName Of course, you should make sure you are in the right database and also that the ProcedureName exists.

Exploring Procedures
Introduction

Probably the simplest procedure you can write would consist of selecting columns from a table. This SELECT operator and applying the techniques we reviewed for data analysis. For example, to create a s that would hold a list of students from a table named Students, you would create the procedure as follow CREATE PROCEDURE GetStudentIdentification AS BEGIN SELECT FirstName, LastName, DateOfBirth, Gender FROM Students END GO

Besides SELECT operations, in a stored procedure, you can perform any of the database operations we far. These include creating and maintaining records, etc.

Practical Learning: Creating a Stored Procedure

1. Make sure you have the Yugo National Bank database created in the Lesson13. If you didn't creat In the Object Explorer, right-click YugoNationalBank and click New Query 2. To start a stored procedure, type the following: USE YugoNationalBank; GO -- ============================================= -- Author: FunctionX -- Create date: Friday, May 25, 2007 -- Description: This stored procedure assigns a -default password to each employee. -- ============================================= CREATE PROCEDURE AssignDefaultPassword AS BEGIN UPDATE dbo.Employees SET Password = 'Password1' FROM dbo.Employees; END ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

GO 3. To create the stored procedure, press F5

Executing a Procedure

To get the results of creating a stored procedure, you must execute it (in other words, to use a stored must call it). To execute a procedure, you use the EXECUTE keyword followed by the name of the proc there are some other issues related to executing a procedure, for now, we will consider that the simples procedure is: EXECUTE ProcedureName Alternatively, instead of EXECUTE, you can use the EXEC keyword: EXEC ProcedureName For example, if you have a procedure named GetStudentIdentification, to execute it, you would type: EXECUTE GetStudentIdentification You can also precede the name of the procedure with its schema, such as dbo. Here is an example: EXECUTE dbo.GetStudentIdentification; You can also precede the name of the schema with the name of the database. Here is an example: EXECUTE ROSH.dbo.GetStudentIdentification;

Practical Learning: Executing a Stored Procedure


1. Delete the contents of the query window and replace it with the following: EXECUTE AssignDefaultPassword; GO 2. To execute the stored procedure, press F5

Using Expressions and Functions

One of the advantages of using a stored procedure is that not only can it produce the same expression a analysis but also it can store such an expression to be recalled any time without having to re-write it ( Based on this, you can create an expression that combines a first and a last name to produce and store a is an example: CREATE PROCEDURE GetStudentIdentification AS BEGIN SELECT FullName = FirstName + ' ' + LastName, DateOfBirth, Gender FROM Students END GO ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

A stored procedure can also call a function in its body. To do this, follow the same rules we revie functions during data analysis. Here is an example of a stored procedure that calls a function: USE ROSH; GO CREATE PROCEDURE GetStudentsAges AS BEGIN SELECT FullName = FirstName + ' ' + LastName, DATEDIFF(year, DateOfBirth, GETDATE()) AS Age, Gender FROM Students END GO Here is an example of executing the procedure:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Practical Learning: Calling a Function in a Stored Procedure


1. Delete the contents of the query window 2. To start a new stored procedure, type the following:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

USE YugoNationalBank; GO -- ============================================= CREATE PROCEDURE CreateUsername AS BEGIN UPDATE dbo.Employees SET Username = LOWER(LEFT(FirstName, 1) + LEFT(LastName, 5)) FROM dbo.Employees; UPDATE dbo.Employees SET EmailAddress = LOWER(LEFT(FirstName, 1) + LEFT(LastName, 5)) + '@yugonationalbank.com' FROM dbo.Employees; END GO 3. To create the stored procedure, press F5 4. Delete the contents of the query window and replace it with the following: EXECUTE CreateUsername; GO 5. To execute the stored procedure, press F5

Arguments and Parameters


Introduction

All of the stored procedures we have created and used so far assumed that the values they needed w table of the database. In some cases, you may need to create a stored procedure that involves values t of the database. On such a scenario, for the procedure to carry its assignment, you would supply it w values.

An external value that is provided to a stored procedure is called a parameter. When you create a stored must also create the parameter if you judge it necessary. When a procedure's creation is equipped with a said that the stored procedure takes an argument. A stored procedure can also take more than one argum

When you execute a stored procedure that takes one or more arguments, you must provide a value for In this case, you are said to pass a value for the argument. There are cases when you don't hav argument.

Passing Arguments

To create a stored procedure that takes an argument, type the formula CREATE PROCEDURE or followed by the name of the procedure, then type the name of the argument starting with @. The para like a column of a table. That is, a parameter must have a name, a data type and an optional length. He you would use: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

CREATE PROCEDURE ProcedureName @ParameterName DataType AS Body of the Procedure

When implementing the stored procedure, you can define what you want to do with the parameter(s), in procedure. One way you can use a parameter is to run a query whose factor the user would provid imagine you want to create a procedure that, whenever executed, would be supplied with a gender, then the list of students of that gender. Since you want the user to specify the gender of students to display, stored procedure that receives the gender. Here is an example: CREATE PROC GetListOfStudentsByGender @Gdr VARCHAR(12) AS SELECT FirstName, LastName, DateOfBirth, HomePhone, Gender FROM Students WHERE Gender = @Gdr

Practical Learning: Creating a Stored Procedure

1. Delete the contents of the query window and, to pass arguments to a stored procedure, type the fol window: USE WattsALoan; GO CREATE PROCEDURE SpecifyCurrentBalance @PmtDate datetime, @EmplID int, @LaID int, @PmtAmt money AS BEGIN -- Get the amount that was lent to the customer DECLARE @AmountOfLoan money; SET @AmountOfLoan = (SELECT las.FutureValue FROM LoanAllocations las WHERE (las.LoanAllocationID = @LaID)); -- If the customer had already made at least one payment, -- get the current balance of the customer's account DECLARE @CurrentBalance money; SET @CurrentBalance = (SELECT MIN(pay.Balance) FROM Payments pay WHERE (pay.LoanAllocationID = @LaID)); -- If the customer has never made a payment (yet), -- to specify the balance, subtract the current payment -- from the original amount of the loan IF @CurrentBalance IS NULL BEGIN ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

INSERT INTO Payments(PaymentDate, EmployeeID, LoanAllocationID, PaymentAmount, Balance) VALUES(@PmtDate, @EmplID, @LaID, @PmtAmt, @AmountOfLoan - @PmtAmt); END -- If the customer had already at least one payment, -- subtract the current payment from the previous balance ELSE BEGIN INSERT INTO Payments(PaymentDate, EmployeeID, LoanAllocationID, PaymentAmount, Balance) VALUES(@PmtDate, @EmplID, @LaID, @PmtAmt, @CurrentBalance - @PmtAmt); END END GO 2. To create the stored procedure, press F5

Executing an Argumentative Stored Procedure

As mentioned already, when executing a stored procedure that takes a parameter, make sure you provid parameter. The syntax used is: EXEC ProcedureName ParameterValue

If the parameter is Boolean or numeric, make sure you provide the value as 0 or for a Boolean value or for the numeric type. If the parameter is a character or a string, type its value in single-quotes. Here is a EXEC ROSH.dbo.GetListOfStudentsByGender 'Male'; Here is an example of executing it:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Notice that we could/should have omitted to include the Gender column in the statement since it would b user.

Another type of stored procedure can be made to take more than one parameter. In this case, create th the section before the AS keyword, separated by a comma. The syntax you would use is: CREATE PROCEDURE ProcedureName @ParameterName1 DataType, @ParameterName2 DataType, @ParameterName_n DataType ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

AS Body of the Procedure Here is an example: USE ROSH; GO CREATE PROCEDURE IdentifyStudentsByState @Gdr varchar(20), @StateOrProvince char(2) AS BEGIN SELECT FullName = LastName + ', ' + FirstName, DATEDIFF(year, DateOfBirth, GETDATE()) AS Age, Gender FROM Students WHERE (Gender = @Gdr) AND (State = @StateOrProvince) END GO

When calling a stored procedure that takes more than one parameter, you must still provide a value for but you have two alternatives. The simplest technique consists of providing a value for each parameter in they appear in the stored procedure. Here is an example: USE ROSH; GO EXEC ROSH.dbo.IdentifyStudentsByState 'Female', 'MD'; GO This would produce:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Alternatively, you can provide the value for each parameter in the order of your choice. Consider the foll that takes 3 arguments: USE ROSH; GO CREATE PROCEDURE IdentifySomeStudents @Gdr varchar(20), @StateOrProvince char(2), ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

@HomeStatus bit AS BEGIN SELECT FullName = LastName + ', ' + FirstName, DATEDIFF(year, DateOfBirth, GETDATE()) AS Age, Gender FROM Students WHERE (Gender = @Gdr) AND (State = @StateOrProvince) AND (SPHome = @HomeStatus) END GO

When calling this type of procedure, you can type the name of each parameter and assign it the corre Here is an example: EXEC IdentifySomeStudents @HomeStatus=1, @StateOrProvince='MD', @Gdr='Female'; Here is an example of executing the procedure:

Practical Learning: Executing an Argumentative Procedure


ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

1. Delete the contents of the code window and, to create a stored procedure, type the following in the USE WattsALoan; GO EXECUTE SpecifyCurrentBalance GO EXECUTE SpecifyCurrentBalance GO EXECUTE SpecifyCurrentBalance GO EXECUTE SpecifyCurrentBalance GO 2. To execute, press F5

'03/25/2004', 2, 1, 249.08; '01/30/2006', 2, 5, 611.93; '04/20/2004', 1, 1, 249.08; '10/28/2006', 2, 4, 134.38;

Default Arguments

Imagine you create a database for a department store and a table that holds the list of items sold in the s

Supposed you have filled the table with a few items as follows:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

ItemNumber ItemCategoryID ItemName 264850 930405 293004 924515 405945 294936 294545 820465 294694 924094 359405 192004 2 4 1 1 3 2 2 2 2 3 3 3 Long-Sleeve Jersey Dress Solid Crewneck Tee Hooded Full-Zip Sweatshirt Plaid Pinpoint Dress Shirt Cool-Dry Soft Cup Bra Ladies Hooded Sweatshirt Cotton Knit Blazer Denim Blazer - Natural Brown Texture-Striped Pleated Dress Pants Iron-Free Pleated Khaki Pants Sunglasses

ItemSize UnitPrice Petite Medium S 36D Medium M Large 44x30 32x32 39.95 12.95 17.85 69.95 15.55 45.75 295.95 75.85 32.85 39.95 15.85

Cotton Comfort Open Bottom Pant XLarge

22 35-36 35.85

Imagine you want to create a mechanism of calculating the price of an item after a discount has been ap a procedure can be created as follows: CREATE PROC CalculateNetPrice @discount Decimal AS SELECT ItemName, UnitPrice - (UnitPrice * @discount / 100) FROM StoreItems This can be executed as follows:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If you are planning to create a stored procedure that takes an argument and know that the argument wi same value most of the time, you can provide that value as parameter but leave a room for othe argument. A value given to an argument is referred to as default. What this implies is that, when th stored procedure, if the user doesn't provide a value for the argument, the default value would be used.

To create a stored procedure that takes an argument that carries a default value, after declaring the va side, type = followed by the desired value. Here is an example applied to the above database: CREATE PROC CalculateDiscountedPrice @discount decimal = 10.00 AS SELECT ItemName, UnitPrice - (UnitPrice * @discount / 100) FROM StoreItems; GO

When executing a stored procedure that takes a default argument, you don't have to provide a value for the default value suits you. Based on this, the above stored procedure can be called as follows:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

If the default value doesn't apply to your current calculation, you can provide a value for the argum example:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Using this same approach, you can create a stored procedure that takes more than one argument with d provide a default value for each argument, after declaring it, type the desired value to its right side. He of a stored procedure that takes two arguments, each with a default value: CREATE PROC CalculateSalePrice @Discount decimal = 20.00, @TaxRate decimal = 7.75 AS SELECT ItemName As [Item Description], UnitPrice As [Marked Price], UnitPrice * @Discount / 100 As [Discount Amt], UnitPrice - (UnitPrice * @Discount / 100) As [After Discount], UnitPrice * @TaxRate / 100 As [Tax Amount], (UnitPrice * @TaxRate / 100) + UnitPrice (UnitPrice * @Discount / 100) + (@TaxRate / 100) As [Net Price] FROM StoreItems; GO Here is an example of executing the procedure:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

When calling a stored procedure that takes more than one argument and all arguments having default v need to provide a value for each argument, you can provide a value for only one or some of the argum procedure can be called with one argument as follows: EXEC CalculateSalePrice2 55.00 In this case, the other argument(s) would use their default value.

We saw that, when calling a stored procedure that takes more than one argument, you didn't have to pr of the arguments in the exact order they appeared in the procedure, you just had to type the name o and assign it the desired value. In the same way, if a stored procedure takes more than one argument arguments have default values, when calling it, you can provide the values in the order of your choic name of each argument and assigning it the desired value. Based on this, the above stored procedure ca only the value of the second argument as follows: EXEC CalculateSalePrice2 @TaxRate = 8.55 In this case, the first argument would use its default value.

Practical Learning: Using Default Arguments


1. Delete the contents of the query window ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

2. To created a new version for a stored procedure we used earlier, type the following in the window: USE WattsALoan; GO DROP PROCEDURE SpecifyCurrentBalance; GO CREATE PROCEDURE SpecifyCurrentBalance @PmtDate datetime, @EmplID int, @LaID int, @PmtAmt money, @Comments Text = '' AS BEGIN -- Get the amount that was lent to the customer DECLARE @AmountOfLoan money; SET @AmountOfLoan = (SELECT las.FutureValue FROM LoanAllocations las WHERE (las.LoanAllocationID = @LaID)); -- If the customer had already made at least one payment, -- get the current balance of the customer's account DECLARE @CurrentBalance money; SET @CurrentBalance = (SELECT MIN(pay.Balance) FROM Payments pay WHERE (pay.LoanAllocationID = @LaID)); -- If the customer has never made a payment (yet), -- to specify the balance, subtract the current payment -- from the original amount of the loan IF @CurrentBalance IS NULL BEGIN INSERT INTO Payments(PaymentDate, EmployeeID, LoanAllocationID, PaymentAmount, Balance, Notes) VALUES(@PmtDate, @EmplID, @LaID, @PmtAmt, @AmountOfLoan - @PmtAmt, @Comments); END -- If the customer had already at least one payment, -- subtract the current payment from the previous balance ELSE BEGIN INSERT INTO Payments(PaymentDate, EmployeeID, LoanAllocationID, PaymentAmount, Balance, Notes) VALUES(@PmtDate, @EmplID, @LaID, @PmtAmt, @CurrentBalance - @PmtAmt, @Comments); END ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

END GO 3. To create the stored procedure, press F5 4. Delete the contents of the query window 5. To use the stored procedure, type the following: USE WattsALoan; GO EXECUTE SpecifyCurrentBalance '07/15/2004', 3, 'The customer sent a double-payment to cover GO EXECUTE SpecifyCurrentBalance '01/26/2007', 1, GO EXECUTE SpecifyCurrentBalance '08/26/2004', 2, GO EXECUTE SpecifyCurrentBalance '02/28/2006', 3, GO EXECUTE SpecifyCurrentBalance '10/24/2007', 2, GO EXECUTE SpecifyCurrentBalance '05/30/2004', 1, GO EXECUTE SpecifyCurrentBalance '02/22/2007', 2, GO EXECUTE SpecifyCurrentBalance '03/23/2006', 2, GO EXECUTE SpecifyCurrentBalance '07/22/2007', 2, 'First regular payment'; GO EXECUTE SpecifyCurrentBalance '12/24/2006', 1, GO EXECUTE SpecifyCurrentBalance '04/25/2006', 3, GO EXECUTE SpecifyCurrentBalance '09/26/2007', 2, GO EXECUTE SpecifyCurrentBalance '09/24/2006', 3, GO EXECUTE SpecifyCurrentBalance '03/25/2007', 2, GO EXECUTE SpecifyCurrentBalance '11/28/2006', 2, 'First Car Payment'; GO EXECUTE SpecifyCurrentBalance '08/28/2007', 1, 'Second payment'; GO 6. Delete the contents of the query window 1, 498.16, this and last month'; 3, 50; 1, 249.08; 5, 611.93; 2, 415.25; 1, 249.08; 3, 20; 5, 611.93; 2, 415.25, 5, 611.93; 5, 611.93; 2, 415.25; 4, 134.38; 3, 25; 5, 611.93, 2, 415.25,

Output Parameters
ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Transact-SQL uses the notion of passing an argument by reference. This type of argument is passed to a is meant to return a value. In other words, you can create a stored procedure that takes a parameter bu the parameter is to carry a new value when the procedure ends so you can use that value as you see fit.

To create a parameter that will return a value from the stored procedure, after the name of the proced the stored procedure to take arguments, type them. Otherwise, omit them. On the other hand, you mu one argument, name it starting with the @ symbol, specify its data type, and enter the OUTPUT keyw Based on this, the basic syntax you can use is: CREATE PROCEDURE ProcedureName @ParameterName DataType OUTPUT AS Body of the Procedure

In the body of the procedure, you can perform the assignment as you see fit. The primary rule you mu before the end of the procedure, you must have specified a value for the OUTPUT argument. That's th argument will hold when the stored procedure exits. Here is an example: CREATE PROCEDURE dbo.CreateFullName @FName varchar(20), @LName varchar(20), @FullName varchar(42) OUTPUT AS SELECT @FullName = @LName + ', ' + @FName GO

When calling the stored procedure, you must pass an argument for the OUTPUT parameter and, once type OUTPUT to the right side of the argument. Remember that the stored procedure would return the means that, after calling the procedure, you can get back the OUTPUT argument and use it as you se example: DECLARE @FirstName varchar(20), @LastName varchar(20), @Full varchar(42) SET @FirstName = 'Melanie'; SET @LastName = 'Johanssen'; EXECUTE dbo.CreateFullName @FirstName, @LastName, @Full OUTPUT SELECT @Full; GO

One of the advantages of using a function or a stored procedure is that it has access to the tables an database. This means that you can access the columns and records as long as you specify the table or th done with a FROM clause associated with a SELECT statement. Consider the following stored proced database that contains a table named Students: USE ROSH; GO CREATE PROCEDURE ShowStudentsFullNames @FullName varchar(42) OUTPUT ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

AS SELECT @FullName = LastName + ', ' + FirstName FROM Students; GO

When you execute this stored procedure, it would work on the records of the table. One of the particula procedure that takes an OUTPUT argument is that it can return only one value. Consider the follow executing the above procedure:

When calling such a procedure, if you don't specify a condition to produce one particular result, the S this case would select the last record. This means that you should always make sure that your stored takes an OUTPUT parameter would have a way to isolate a result. If the stored procedure proce statement, you can use a WHERE condition. Here is an example of such a procedure: USE ROSH; GO CREATE PROCEDURE ShowStudentsFullNames @FullName varchar(42) OUTPUT AS SELECT @FullName = LastName + ', ' + FirstName FROM Students WHERE StudentID = 8; GO 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 ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

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 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, yo assignment the function must perform. After performing this assignment, just before the END keyword, y the value that the function returns. This is done by typing the RETURN keyword followed by an expre 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 Here is another example: CREATE FUNCTION CalculateWeeklySalary() RETURNS Decimal(8, 2) AS BEGIN RETURN 880.44 ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

END; GO

Function Calling

After a function has been created, you can use the value it returns. Using a function is also referred to call a function, you must qualify its name. To do this, type the name of the database in which it was crea the period operator, followed by dbo, followed by the period operator, followed by the name of the parentheses. The formula to use is: DatabaseName.dbo.FunctionName()

Because a function returns a value, you can use that value as you see fit. For example, you can use SELECT to display the function's value in a query window. Here is an example that calls the above Additio PRINT Exercise.dbo.GetFullName();

As an alternative, to call a function, in the Object Explorer, right-click its name, position the mouse on Sc SELECT To, and click New Query Editor Window.

Renaming a Function
To rename a function, in the Object Explorer, right-click it and click Rename. Type the desired new Enter.

Modifying a Function

As mentioned already, in the body of the function, you define what the function is supposed to tak minimum, a function can return a simple number, typed on the right side of the RETURN keyword. Here CREATE FUNCTION Addition() RETURNS int BEGIN RETURN 1 END

You can also declare new variables in the body of the function to help in carrying the assignment. A var the body of a function is referred to as a local variable. Once such a variable has been declared, it can other variable. Here is an example: CREATE FUNCTION Addition() RETURNS int BEGIN DECLARE @Number1 int SET @Number1 = 588 RETURN @Number1 + 1450 END

A Parameterized Function

To create a function that takes a parameter, specify a name and the type of value of the parameter(s) in Here is an example: CREATE FUNCTION Addition(@Number1 Decimal(6,2)) ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

When a function takes a parameter, in the body of the function, you can use the parameter as if you kn long as you respect the type of that value. Here is an example: CREATE FUNCTION Addition(@Number1 Decimal(6,2)) RETURNS Decimal(6,2) BEGIN RETURN @Number1 + 1450 END

Calling a Parameterized Function

When you call a function that takes one parameter, you must supply a value for that argument. To d value of the parameter in the parentheses of the function. Here is an example:

A Function With Various Arguments

Instead of only one parameter, you can also create a function that takes more than one parameter. In th the arguments in the parentheses of the function with a comma. Here is an example: CREATE FUNCTION Addition(@Number1 Decimal(6,2), @Number2 Decimal(6,2))

Once again, in the body of the function, you can use the parameters as if you already knew their valu declare local variables and involve them with parameters as you see fit. Here is an example: CREATE FUNCTION Addition(@Number1 Decimal(6,2), @Number2 Decimal(6,2)) RETURNS Decimal(6,2) BEGIN DECLARE @Result Decimal(6,2) SET @Result = @Number1 + @Number2 RETURN @Result END; GO When calling a function that takes more than one parameter, in the parentheses of the function, provide parameter, in the exact order they appear in the parentheses of the function. Here is an example: ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

PRINT Variables1.dbo.Addition(1450, 228); You can also pass the names of already declared and initialized variables. Here is an example that function: DECLARE @Nbr1 Decimal(6,2), @Nbr2 Decimal(6,2) SET @Nbr1 = 4268.55 SET @Nbr2 =26.83 SELECT @Nbr1 As First, @Nbr2 As Second, Variables1.dbo.Addition(@Nbr1, @Nbr2) AS Result This would produce:

Code Example 1:
create table test1 (descr varchar(32)) go insert test1 select 'Quick demo of' union select 'instead of triggers' go create trigger tr_test1_io on test1 instead of update as BEGIN ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

select descr as 'Inserted Columns' from inserted select descr as 'Deleted Columns' from deleted select descr as 'Table test1' from test1 END -- trigger def go update test1 set descr = NULL go drop table test1

Code Example 2:
create table country ( countryID int identity, countryName varchar(32), } go create table city ( cityID int identity , CityName varchar(32), countryID int, ) go create view v_geography as select countryName, cityName from country inner join city on country.countryID = city.countryID go create trigger tr_v_geography_io on v_geography instead of insert as BEGIN insert country (countryName) select distinct inserted.countryName from inserted left join country on inserted.countryName = country.countryName where country.countryName IS NULL /*** Exclude countries already in the table ***/ insert city (cityName, countryID) select distinct inserted.cityName, country.countryID from inserted inner join country on inserted.countryName = country.countryName left join city on inserted.cityName = city.cityName where city.cityName IS NULL /*** Exclude cities already in the table ***/ END -- trigger def go insert select select select v_geography 'England', 'London' UNION 'England', 'Manchester' UNION 'Japan', 'Tokyo' UNION

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

select 'Japan', 'Osaka' UNION select 'USA', 'Washington DC' UNION select 'USA', 'New York'

Following is the syntax for DDL triggers.

CREATE TRIGGER trigger_name

ON { ALL SERVER | DATABASE }

[ WITH <ddl_trigger_option> [ ,...n ] ]

{ FOR | AFTER } { event_type | event_group } [ ,...n ]

AS { sql_statement [ ; ] [ ...n ] | EXTERNAL NAME < method specifier > [ ; ] }

DDL triggers can be created in either in the Database or the Server. If you want to monitor table creations and drops, you should create DDL trigger on the database, while to monitor operations like database creations you should create a DDL trigger on the Server. Take a simple example of creating a database.

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

CREATE DATABASE [DDL_TRIGGERS_DB] Let us assume that we want to log all the new table creations. We will log all the events in some other database called DDL_Trigger_Log in a table which has following schema. CREATE TABLE [dbo].[tblDDLEventLog]( [ID] [int] IDENTITY(1,1) NOT NULL, [EventTime] [datetime] NULL, [EventType] [varchar](15) NULL, [ServerName] [varchar](25) NULL, [DatabaseName] [varchar](25) NULL, [ObjectType] [varchar](25) NULL, [ObjectName] [varchar](25) NULL, [UserName] [varchar](15) NULL, [CommandText] [varchar](max) NULL,)

Then we need to create a DDL trigger so that all the relevent event data is updated in the above table. Follwing will be the DDL trigger. CREATE TRIGGER [ddltrg_CREATE_TABLE_LOG] ON DATABASE -- Create Database DDL Trigger FOR CREATE_TABLE -- Trigger will raise when creating a Table AS ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

SET NOCOUNT ON DECLARE @xmlEventData XML -- Capture the event data that is created SET @xmlEventData = eventdata() -- Insert information to a EventLog table INSERT INTO DDL_Trigger_Log.dbo.tblDDLEventLog ( EventTime, EventType, ServerName, DatabaseName, ObjectType, ObjectName, UserName, CommandText ) SELECT REPLACE(CONVERT(VARCHAR(50), @xmlEventData.query('data(/EVENT_INSTANCE/PostTime)')),

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

'T', ' '), CONVERT(VARCHAR(15), @xmlEventData.query('data(/EVENT_INSTANCE/EventType)')), CONVERT(VARCHAR(25), @xmlEventData.query('data(/EVENT_INSTANCE/ServerName)')), CONVERT(VARCHAR(25), @xmlEventData.query('data(/EVENT_INSTANCE/DatabaseName)')), CONVERT(VARCHAR(25), @xmlEventData.query('data(/EVENT_INSTANCE/ObjectType)')), CONVERT(VARCHAR(25), @xmlEventData.query('data(/EVENT_INSTANCE/ObjectName)')), CONVERT(VARCHAR(15), @xmlEventData.query('data(/EVENT_INSTANCE/UserName)')), CONVERT(VARCHAR(MAX), @xmlEventData.query('data(/EVENT_INSTANCE/TSQLCommand/CommandText)')) GO USE AdventureWorks; GO -- Turn recursive triggers ON in the database. ALTER DATABASE AdventureWorks SET RECURSIVE_TRIGGERS ON GO CREATE TABLE emp_mgr ( emp char(30) PRIMARY KEY, mgr char(30) NULL FOREIGN KEY REFERENCES emp_mgr(emp), NoOfReports int DEFAULT 0 ) GO CREATE TRIGGER emp_mgrins ON emp_mgr FOR INSERT AS DECLARE @e char(30), @m char(30) DECLARE c1 CURSOR FOR SELECT emp_mgr.emp ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

FROM

emp_mgr, inserted

WHERE emp_mgr.emp = inserted.mgr OPEN c1 FETCH NEXT FROM c1 INTO @e WHILE @@fetch_status = 0 BEGIN UPDATE emp_mgr SET emp_mgr.NoOfReports = emp_mgr.NoOfReports + 1 -- Add 1 for newly WHERE emp_mgr.emp = @e FETCH NEXT FROM c1 INTO @e END CLOSE c1 DEALLOCATE c1 GO -- This recursive UPDATE trigger works assuming: --AS IF UPDATE (mgr) BEGIN UPDATE emp_mgr SET emp_mgr.NoOfReports = emp_mgr.NoOfReports + 1 -- Increment mgr's FROM inserted WHERE emp_mgr.emp = inserted.mgr UPDATE emp_mgr SET emp_mgr.NoOfReports = emp_mgr.NoOfReports - 1 -- Decrement mgr's FROM deleted WHERE emp_mgr.emp = deleted.mgr END GO -- Insert some test data rows. INSERT emp_mgr(emp, mgr) VALUES ('Harry', NULL) INSERT emp_mgr(emp, mgr) VALUES ('Alice', 'Harry') INSERT emp_mgr(emp, mgr) VALUES ('Paul', 'Alice') ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com -- (no. of reports) by 1 -- for the new report. -- (no. of reports) by -- 1 for the new report. 1. Only singleton updates on emp_mgr. 2. No inserts in the middle of the org tree. -- added employee.

CREATE TRIGGER emp_mgrupd ON emp_mgr FOR UPDATE

INSERT emp_mgr(emp, mgr) VALUES ('Joe', 'Alice') INSERT emp_mgr(emp, mgr) VALUES ('Dave', 'Joe') GO SELECT * FROM emp_mgr GO -- Change Dave's manager from Joe to Harry UPDATE emp_mgr SET mgr = 'Harry' WHERE emp = 'Dave' GO SELECT * FROM emp_mgr GO
Here are the results before the update. Copy Code

emp Alice Dave Harry Joe Paul


Here are the results after the update. Copy Code

mgr Harry Joe NULL Alice Alice

NoOfReports 2 0 1 1 0

------------------------------ ----------------------------- -----------

emp Alice Dave CREATE TABLE t1

mgr Harry

NoOfReports 2

------------------------------ ----------------------------- -----------

(a int NULL, b int NOT NULL DEFAULT 99) GO CREATE TRIGGER t1trig ON t1 FOR INSERT, UPDATE ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

AS IF UPDATE(a) AND UPDATE(b) PRINT 'FIRING' GO

IF EXISTS (SELECT * FROM sys.triggers WHERE parent_class = 0 AND name = 'safety') DROP TRIGGER safety ON DATABASE; GO CREATE TRIGGER safety ON DATABASE FOR DROP_TABLE, ALTER_TABLE AS PRINT 'You must disable Trigger "safety" to drop or alter tables!' ROLLBACK; GO DISABLE TRIGGER safety ON DATABASE; GO

A. Use simple cursor and syntax The result set generated at the opening of this cursor includes all rows and all columns in the authors table of the pubs database. This cursor can be updated, and all updates and deletes are represented in fetches made against this cursor. FETCH NEXT is the only fetch available because the SCROLL option has not been specified.

DECLARE authors_cursor CURSOR FOR SELECT * FROM authors OPEN authors_cursor FETCH NEXT FROM authors_cursor
B. Use nested cursors to produce report output This example shows how cursors can be nested to produce complex reports. The inner cursor is declared for each author.

SET NOCOUNT ON DECLARE @au_id varchar(11), @au_fname varchar(20), @au_lname varchar(40),


ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

@message varchar(80), @title varchar(80) PRINT "-------- Utah Authors report --------" DECLARE authors_cursor CURSOR FOR SELECT au_id, au_fname, au_lname FROM authors WHERE state = "UT" ORDER BY au_id OPEN authors_cursor FETCH NEXT FROM authors_cursor INTO @au_id, @au_fname, @au_lname WHILE @@FETCH_STATUS = 0 BEGIN PRINT " " SELECT @message = "----- Books by Author: " + @au_fname + " " + @au_lname PRINT @message -- Declare an inner cursor based -- on au_id from the outer cursor. DECLARE titles_cursor CURSOR FOR SELECT t.title FROM titleauthor ta, titles t WHERE ta.title_id = t.title_id AND ta.au_id = @au_id -- Variable value from the outer cursor OPEN titles_cursor FETCH NEXT FROM titles_cursor INTO @title IF @@FETCH_STATUS <> 0 PRINT " <<No Books>>" WHILE @@FETCH_STATUS = 0 BEGIN SELECT @message = " " + @title PRINT @message FETCH NEXT FROM titles_cursor INTO @title END CLOSE titles_cursor DEALLOCATE titles_cursor
ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

-- Get the next author. FETCH NEXT FROM authors_cursor INTO @au_id, @au_fname, @au_lname END CLOSE authors_cursor DEALLOCATE authors_cursor GO -------- Utah Authors report ------------ Books by Author: Anne Ringer The Gourmet Microwave Is Anger the Enemy? ----- Books by Author: Albert Ringer Is Anger the Enemy? Life Without Fear

How do I send e-mail from SQL Server?


SQL Server has the ability to send mail without being triggered from ASP. So, if you have an application that needs to e-mail users once a month, or on their birthday, or to send you details every day about what went on in the database that day, you can set up a job that wakes up and sends e-mail. Similarly, you can call extended stored procedures to send mail on demand (e.g. every time a stored procedure fires). First off, make sure your SQL Server Mail account is set up correctly - see the following articles:
Configuring and Managing SQL Mail An Introduction to SQL Mail and SQLAgent... KB #870675 How to send and receive e-mail with the SQL Mail feature in SQL Server 2000 KB #153159 HOW TO: Troubleshoot SQL Mail with Microsoft Exchange Server KB #263556 INF: How to Configure SQL Mail ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

KB #274330 FIX: Sending Open Files as Attachment in SQL Mail Fails KB #279867 FIX: Sending Maintenance Report by E-mail to Operator Fails KB #281293 FIX: SQL Mail 2000 Needs Microsoft Outlook 2000 Client KB #293422 PRB: xp_sendmail Using a Microsoft Exchange 2000 Mailbox Fails KB #311231 INF: Frequently Asked Questions - SQL Server - SQL Mail KB #315886 INF: Common SQL Mail Problems KB #321183 HOW TO: Troubleshoot Your SQL Mail Issue KB #811035 PRB: The xp_sendmail Stored Procedure Fails KB #820220 PRB: 0x80070005 or 0x80040005 Error Occurs When You Send E-Mail KB #833045 The xp_sendmail extended stored procedure does not run [...]

(For plenty of information on using XP_SendMail, see http://tinyurl.com/1d29.) If you can not or will not configure SQL Mail, or you are frustrated with getting it to work, you can use CDO (see KB #312839) or Gert Draper's XP_SMTP_SendMail (from XPSMTP). I prefer the XP_SMTP_SendMail procedure over both CDO and SQL Mail. XP_SMTP_SendMail is an extended stored procedure that will send mail through any valid SMTP server you specify, and supports HTML formatting. This makes sending mail very flexible, especially if your SQL Server is not a part of a domain, or you're not running Exchange - and you don't have or don't want to install CDO on your database server(s).

To fire off e-mail on demand Let's say you want to send an e-mail from within a stored procedure called foo. You can do it like this: With XP_SendMail:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

CREATE PROCEDURE dbo.foo AS BEGIN SET NOCOUNT ON -- do some other actions DECLARE @body VARCHAR(1024) SET @body = 'foo was fired '+ CONVERT(VARCHAR, GETDATE()) EXEC master..xp_sendmail @recipients='you@you.com', @message = @body, @subject = 'foo was fired.' END -- or you can do it conditionally: CREATE PROCEDURE dbo.foo AS BEGIN SET NOCOUNT ON -- do some other action IF @@ROWCOUNT > 0 BEGIN DECLARE @body VARCHAR(1024) SET @body = 'foo was fired ' + CONVERT(VARCHAR, GETDATE()) + CHAR(13) + CHAR(10) + CONVERT(VARCHAR, @@ROWCOUNT) EXEC master..xp_sendmail @recipients='you@you.com', @message = @body, @subject = 'foo was fired.' END END

With XP_SMTP_SendMail (which assumes you are running SQL Server 7.0 or higher, have installed XP_SMTP_SendMail, and have a valid and properly configured SMTP Server):

CREATE PROCEDURE dbo.foo AS BEGIN SET NOCOUNT ON -- do some other actions DECLARE @body VARCHAR(1024) SET @body = 'foo was fired '+ CONVERT(VARCHAR, GETDATE()) EXEC master..xp_smtp_sendmail @TO = 'you@you.com', @from = 'someone@somewhere.com', @message = @body, @subject = 'foo was fired.',

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

@server = 'smtp.yourdomain.com' END -- or you can do it conditionally: CREATE PROCEDURE dbo.foo AS BEGIN SET NOCOUNT ON -- do some other action IF @@ROWCOUNT > 0 BEGIN DECLARE @body VARCHAR(1024) SET @body = 'foo was fired ' + CONVERT(VARCHAR, GETDATE()) + CHAR(13) + CHAR(10) + CONVERT(VARCHAR, @@ROWCOUNT) EXEC master..xp_smtp_sendmail @TO = 'you@you.com', @from = 'someone@somewhere.com', @message = @body, @subject = 'foo was fired.', @server = 'smtp.yourdomain.com' END END

If you need to send an attachment, you can simply add the following parameter:

@attachments = 'c:\attachment.txt'

CDO.Message This sample assumes you are running Windows 2000 or higher, have a user that has access to sp_OA* procedures, and have a valid and properly configured SMTP server:

CREATE PROCEDURE dbo.sendMail_With_CDOMessage @to VARCHAR(64), @subject VARCHAR(255), @body VARCHAR(1024) AS BEGIN SET NOCOUNT ON

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

DECLARE @handle INT, @return INT, @s VARCHAR(64), @sc VARCHAR(1024), @up CHAR(27), @from VARCHAR(64), @server VARCHAR(255), @filename VARCHAR(255) SET @s = '"http://schemas.microsoft.com/cdo/configuration/' SELECT @s = 'Configuration.Fields(' + @s, @up = 'Configuration.Fields.Update', @from = 'someone@somewhere.com', @server = 'smtp.yourdomain.com' -- or IP address, e.g. '127.0.0.1' -- if you want an attachment: ,@filename = 'C:\folder\file.ext'

EXEC @return SET @sc = @s EXEC @return SET @sc = @s EXEC @return EXEC @return EXEC @return EXEC @return EXEC @return EXEC @return

= + = + = = = = = =

sp_OACreate 'CDO.Message', @handle OUT 'sendusing").Value' sp_OASetProperty @handle, @sc, '2' 'smtpserver").Value' sp_OASetProperty @handle, @sc, @server sp_OAMethod @handle, @up, NULL sp_OASetProperty @handle, 'To', @to sp_OASetProperty @handle, 'From', @from sp_OASetProperty @handle, 'Subject', @subject sp_OASetProperty @handle, 'TextBody', @body

IF @filename IS NOT NULL EXEC @return = sp_OAMethod @handle, 'AddAttachment', NULL, @filename EXEC @return = sp_OAMethod @handle, 'Send', NULL IF @return <> 0 BEGIN PRINT 'Mail failed.' IF @from IS NULL PRINT 'From address undefined.' ELSE PRINT 'Check that server is valid.' ELSE PRINT 'Mail sent.' EXEC @return = sp_OADestroy @handle END GO

You can also use the component ASPEmail (from www.aspemail.com) in this way. There is a code
ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

sample at support.persists.com.

To schedule mail Now, let's say you have a stored procedure that checks a table for birthdays, and e-mails a happy birthday to all matches. It might look like this (this assumes XP_SMTP_SendMail is the method you're using):

CREATE TABLE dbo.birthdays ( fullname VARCHAR(128), email VARCHAR(128), birthdate SMALLDATETIME ) GO INSERT birthdays VALUES('AB', 'ab@nonexists.com', '19740201') INSERT birthdays VALUES('CB', 'cb@nonexists.com', '19870123') INSERT birthdays VALUES('TC', 'tc@nonexists.com', '20011227') GO -- and include your own address, with today's date, for testing! CREATE PROCEDURE dbo.proc_happyBirthday AS BEGIN SET NOCOUNT ON -- if you have more than 80 matches on any -- possible day, you may want to use a cursor -- instead - this will only handle 8000 chars. DECLARE @BCCList VARCHAR(8000) SET @BCCList = '' ----concat the BCC list for people with birthdays of today. Note that this job won't run on February 29th of non-leap years, so you may want to add logic for that...

SELECT @BCCList = @BCCList + ';' + COALESCE(email, '') FROM Birthdays WHERE MONTH(birthdate) = MONTH(GETDATE()) AND DAY(birthdate) = DAY(GETDATE()) -- trim off leading ';' character from concatenation

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

SET @BCCList = SUBSTRING(@BCCList, 2, LEN(@BCCList)) EXEC master..xp_smtp_sendmail @TO = 'you@you.com', @BCC = @BCCList, @from = 'someone@somewhere.com', @subject = 'Happy Birthday to you!', @message = 'You belong in a zoo!', @server = 'smtp.yourdomain.com' END GO

Currently, you might be invoking this stored procedure manually, or having a scheduled ASP / VBS script execute the stored procedure through ADO. Wouldn't it be nice to have the database take care of this, without involving other machines and code? Make sure SQL Server agent is running. In Enterprise Manager, expand the server in question, and expand the Management node. Make sure SQL Server Agent is started.

If it is not running, right-click it and hit Start. Right-click and hit properties, and on the advanced tab, make sure SQL Server Agent is set to Auto-restart if that option is available:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Next, you will need to create a job. Under SQL Server agent, right-click Jobs and choose 'New Job...' You will see the following dialog:

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

On the General tab, name the job (e.g. SendBirthdayNotices). On the Steps tab, click New... and enter 'Step 1' into the Step Name: box. Switch the database dropdown to the database where your stored procedure lives, make sure 'Transact-SQL' is selected, and enter 'EXEC proc_happyBirthday'. On the Schedules tab, click New Schedule... and enter 'Schedule 1' in the Name: box. Make sure 'enabled' is checked, and click the 'Change...' button. Set up a schedule that makes sense... e.g. daily at noon or daily at 5:00 am. The interface may look a bit daunting but it's pretty simple to configure.

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Now, you can monitor your job's progress in the jobs view to see last/next run dates, and right-click the job itself to see the job history. You can also right-click the job and start it now (e.g. if you created it AFTER the scheduled run time but still want it to run today).

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Job failure notifications When moving away from SQL Mail, one thing that people have a problem with is losing their ability to send notifications when jobs fail. The current options require SQL Mail to be installed, but is there a way around it? Of course there is. Right-click the job in question, and hit Properties. Create an additional step in the job (by clicking the New button), and call this step "E-mail on failure." Make sure it is the *last* step. On the general tab of the step's properties, select the correct database, and then enter the following for the command:

EXEC master..xp_smtp_sendmail @TO = 'you@you.com', @from = 'someone@somewhere.com', @subject = '<job name> failed.', @server = 'smtp.yourdomain.com'

Of course, you can add @message and other parameters if you wish. On the advanced tab of the step's properties, set both the on success and on failure actions to "Quit the job reporting failure." As you'll see in a minute, this step will only ever be fired if a previous step fails, and you probably want to maintain other tracking (such as the Windows event log) when the job fails. Hit Apply and OK. Now, here's where the magic happens. Go to the previous step, and select the Edit button. On the Advanced tab, change the on failure action to "Go to the next step." (You can choose go to step n, but this might cause order/dependency problems when scripting the job.) Make sure the on success action is set to "Quit the job reporting success." Hit Apply and OK. You may be asked if you're really sure this is the way you want it set up. Feel free to double-check before committing. You can get more complicated, for example if a job has many steps, each step can be set to fail over to a different "e-mail on failure" step.

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

Alerts One element that XP_SMTP_SendMail does not cover is SQL Agent alerts. People have gone the SMTP route, in an effort to avoid Outlook / Exchange / MAPI altogether, only to find that they still need to implement those technologies in order to receive alerts via e-mail. Well, not any more. A colleague has published a free SMTP Alerter tool that works alongside XP_SMTP_SendMail to generate alerts and send them via SMTP.

ABACUS SYSTEM, C-38 Market Building, Saheed Nagar, Bhubaneswar-07, Mobile: 9338545886, 0674-3204701, Email: kcsahoo_net@rediffmail.com

You might also like