Introduction Sql Server

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Introduction Sql Server as PDF for free.

More details

  • Words: 21,819
  • Pages: 102
Introduction Probably before using a database, you must first have one. A database is primarily a group of computer files that each has a name and a location. Just as there are different ways to connect to a server, in the same way, there are also different ways to create a database.

The Name of a Database Probably the most important requirement of creating a database is to give it a name. The SQL is very flexible when it comes to names. In fact, it is very less restrictive than most other computer languages. Still, there are rules you must follow when naming the objects in your databases: •

A name can start with either a letter (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, or Z), a digit (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9), an underscore (_) or a non-readable character. Examples are _n, act, %783, Second



After the first character (letter, digit, underscore, or symbol), the name can have combinations of underscores, letters, digits, or symbols. Examples are _n24 or act_52_t



A name can include spaces. Example are c0untries st@ts, govmnt (records), or gl0b# $urvey||

Microsoft SQL Server Primary Settings Introduction When you install Microsoft SQL Server, it also installs 4 databases named master, model, msdb, and tempdb. These databases will be for internal use. This means that you should avoid directly using them, unless you know exactly what you are doing.

The System Databases One of the databases installed with Microsoft SQL Server is named master. This database holds all the information about the server on which your MS SQL Server is installed. For example, we saw earlier that, to perform any operation on the server, you must login. The master database identifies any person, called a user, who accesses the database, about when and how. Besides identifying who accesses the system, the master database also keeps track of everything you do on the server, including creating and managing databases. You should not play with the master database; otherwise you may corrupt the system. For example, if the master database is not functioning right, the system would not work.

A Namespace A namespace is a technique of creating a series of items that each has a unique name. For example, if you start creating many databases, there is a possibility that you may risk having various databases with the same name. If using a namespace, you can isolate the databases in various namespaces. In reality, to manage many other aspects of your database server, you use namespaces and you put objects, other than databases, within those namespaces. Therefore, a namespace and its content can be illustrated as follows:

Notice that there are various types of objects within a namespace.

The Schema of a Database Within a namespace, you can create objects as you wish. To further control and manage the objects inside of a namespace, you can put them in sub-groups called schemas. Therefore, a schema is a group of objects within a namespace. This also means that, within a namespace, you can have as many schemas as you want:

To manage the schemas in a namespace, you need a way to identify each schema. Based on this, each schema must have a name. In our illustration, one schema is named Schema1. Another schema is named Schema2. Yet another schema is named Schema_n. Inside of a schema, two objects cannot have the same name, but an object in one schema can have the same name as an object in another schema. Based on this, if you are accessing an object within its schema, you can simply use its name, since that name would be unique. On the other hand, because of the implied possibility of dealing with objects with similar names in your server, when accessing an object outside of its schema, you must qualify it. To do this, you would type the name of the schema that contains the object you want to use, followed by the period operator, followed by the name of the object you want to use. From our illustration, to access the Something1 object that belongs to Schema1, you would type: Schema1.Something1 There are two types of schemas you can use, those built-in and those you create. When Microsoft SQL Server is installed, it also creates a few schemas. One of the schemas is called sys. The sys schema contains a list of some of the objects that exist in your system. One of these objects is called databases (actually, it's a view). When you create a database, its name is entered in the databases object using the same name you gave it.

Comments

/* First find out if the database we want to create exists already */

Create database GO

CREATE DATABASE RealEstate1;

Deleting a Database Using SQL To delete a database in SQL Query Analyzer, you use the DROP DATABASE expression followed by the name of the database. The formula used is: DROP DATABASE DatabaseName;

The Current Database While writing code in a Query Window, you should always know what database you are working on, otherwise you may add code to the wrong database. To programmatically specify the current database, type the USE keyword followed by the name of the database. The formula to use is: USE DatabaseName

PRINT Something Like every language, SQL ships with some words used to carry its various operations. One of these words is PRINT. To display something in plain text as a result of a statement, type PRINT followed by what to display. Therefore, PRINT uses the following formula: PRINT WhatToPrint

SELECT SELECT 'Hourly Salary', 24.85

Nesting a SELECT Statement When you create a SELECT statement, what is on the right side of SELECT must be a value. Here is an example: SELECT 226.75; Based on this definition, instead of just being a value, the thing on the right side of SELECT must be able to produce a value. As we will see in the next sections, you can create algebraic operation on the right side of SELECT. Because we mentioned that the thing on the right side must produce a result, you can as well use another SELECT statement that it itself evaluates to a result. To distinguish the SELECT sections, the second one should be included in parentheses. Here is an example: SELECT (SELECT 448.25);

GO When one SELECT statement is created after another, the second is referred to as nested. Just as you can nest one SELECT statement inside of another, you can also nest one statement in another statement that itself is nested. Here is an example: SELECT (SELECT (SELECT 1350.75));

SELECT This AS That In the above introductions, we used either PRINT or SELECT to display something in the query window. One of the characteristics of SELECT is that it can segment its result in different sections. SELECT represents each value in a section called a column. Each column is represented with a name also called a caption. By default, the caption displays as "(No column name)". If you want to use your own caption, on the right side of an expression, type the AS keyword followed by the desired caption. The item on the right side of the AS keyword must be considered as one word. Here is an example: SELECT 24.85 AS HourlySalary; This would produce:

You can also include the item on the right side of AS in single-quotes. Here is an example: SELECT 24.85 AS 'HourlySalary'; SELECT 24.85 AS 'Hourly Salary';

If you create different sections, separated by a comma, you can follow each with AS and a caption. Here is an example: SELECT 'James Knight' As FullName, 20.48 AS Salary;

Unary Operators The Positive Operator + A unary operator is an operator that performs its operation on only one operand. Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive: -∞

-6

-5

-4

-3

-2

-1

1

2

3

4

5

6

+∞

1

2

3

4

5

6

+∞

0 -∞

-6

-5

-4

-3

-2

-1

A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand. The positive unary operator, when used, must be positioned on the left side of its operand, never on the right side. As a mathematical convention, when a value is positive, you do not need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value does not display a sign, it is referred as unsigned as we learned in the previous lesson. To express a variable as positive or unsigned, you can just type it. here is an example: PRINT +1250

The Negative Operator As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by - is referred to as negative. The - sign must be typed on the left side of the number it is used to negate. Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a sign to its left. Here is an example that uses two variables. One has a positive value while the other has a negative value: SELECT -1250

Binary Operators The Addition An operator is referred to as binary if it operates on two operands.

The addition, also called the sum, is an operation used to add one item to another. The addition is performed using the + sign. To get the addition of two values, you type + between them, as in Value1 to Value2. After the addition has been performed, you get a new value that you can make available or display to the user. You can perform the addition on two numbers. Here is an example: PRINT 125 + 4088 In Transact-SQL, you can also perform the addition on text. Here is an example: PRINT 'Henry ' + 'Kono' You can also add more than two values, like a + b + c. The order you use to add two or more values doesn't matter. This means Value1 + Value2 is the same as Value2 + Value1. In the same way a + b + c is the same as a + c + b the same as b + a + c and the same as c + b + a.

The Subtraction The subtraction operation, sometimes called the difference, is used to take out or subtract one value from another value. It is essentially the opposite of the addition. The subtraction is performed with the - sign. Here is an example: PRINT 1240 - 608 Unlike the addition, the subtraction operation is not associative. This means that a - b - c is not necessarily equal to c - b - a. This is illustrated in the following statements: PRINT 128 - 42 - 5 PRINT 5 - 42 - 128 This would produce: 81 -165 Notice that both operations of the addition convey the same result. In the subtraction section, the numbers follow the same order but a different operation; and the last two operations render different results.

The Multiplication The multiplication allows adding one value to itself a certain number of times, set by a second value. As an example, instead of adding a value to itself in this

manner: a + a + a + a, since the variable a is repeated over and over again, you could simply find out how many times a is added to itself, then multiply a by that number which, is this case, is 4. This would mean adding a to itself 4 times, and you would get the same result. The multiplication is performed with the * sign. Just like the addition, the multiplication is associative: a * b * c = c * b * a. Here is an example: PRINT 128 * 42 This would produce 5376

The Division The division operation is similar to cutting an item in pieces or fractions of a set value. Therefore, the division is used to get the fraction of one number in terms of another. The division is performed with the forward slash /. Here is an example: PRINT 128 / 42 This would produce 3 When performing the division, be aware of its many rules. Never divide by zero (0). Make sure that you know the relationship(s) between the numbers involved in the operation.

The Modulo In the above division, 128/42, the result is 3. When you multiply 42 by 3, as in 42*3, you get 126. In some cases, you may be interested in knowing the amount that was left out after the operation. The modulo operation is used to get the remainder of a division as a natural number. The remainder operation is performed with the percent sign (%). Here is an example: PRINT 128 % 42 This would produce 2.

Parentheses Like most computer languages, Transact-SQL uses parentheses to isolate a group of items that must be considered as belonging to one entity. For example, as we will learn soon, parentheses allow a function to delimit the list of its arguments. Parentheses can also be used to isolate an operation or an expression with regards to another operation or expression. For example, when studying the algebraic operations, we saw that the subtraction is not associative and can lead to unpredictable results. In the same way, if your operation involves various operators such as a mix of addition(s) and subtraction(s), you can use parentheses to specify how to proceed with the operations, that is, what operation should (must) be performed first. Here is an example: PRINT (154 - 12) + 8 PRINT 154 - (12 + 8) This would produce:

150 134 As you can see, using the parentheses controls how the whole operation would proceed. This difference can be even more accentuated if your operation includes 3 or more operators and 4 or more operands. Here is another example of a nested SELECT statement that uses parentheses: SELECT (SELECT 448.25 * 3) + (SELECT 82.28 - 36.04); GO Thi

Bit Manipulations Introduction When you use a value in your database or application, the value must be stored somewhere in the computer memory using a certain amount of space. A value occupies space that resembles a group of small boxes. In our human understanding, it is not always easy to figure out how a letter such as as B is stored in 7 seven small boxes when we know that B is only one letter. Bit manipulation or a bit related operation allows you to control how values are stored in bits. This is not an operation you will need to perform very often, especially not in the early stages of your database. Nevertheless, bit operations (and related overloaded operators) are present in all or most programming environments, so much that you should be aware of what they do or what they offer.

Bits Operators: The Bitwise NOT Operator ~ One of the operations you can perform on a bit consists of reversing its value. That is, if a bit holds a value of 1, you may want to change it to 0 and vice-versa. This operation can be taken care of by the bitwise NOT operator that is represented with the tilde symbol ~ The bitwise NOT is a unary operator that must be placed on the left side of its operand as in ~Value Here is an example: PRINT ~158 To perform this operation, the Transact-SQL interpreter considers each bit that is part of the operand and inverts the value of each bit from 1 to 0 or from 0 to 1 depending on the value the bit is holding. This operation can be resumed in the following table:

Bit

~Bit

1 0

0 1

Consider a number with a byte value such as 248. In our study of numeric systems, we define how to convert numbers from one system to another. Based on this, the binary value of decimal 248 is 1111 1000 (and its hexadecimal value is 0xF8). If you apply the bitwise NOT operator on it to reverse the values of its bits, you would get the following result:

Value 1 ~Value 0

1 0

1 0

1 0

1 0

0 1

0 1

0 1

Bits Comparison: The Bitwise AND Operator & The bitwise & is a binary operator that uses the following syntax Operand1 & Operand2 This operator considers two values and compares the bit of each with the corresponding bit of the other value. If both corresponding bits are 1, the comparison produces 1. Otherwise, that is, if either bit is 0, the comparison produces 0. This comparison is resumed as follows:

Bit1 0 1 0 1

Bit2 0 0 1 1

Bit1 & Bit2 0 0 0 1

Imagine you have two byte values represented as 187 and 242. Based on our study of numeric systems, the binary value of decimal 187 is 1011 1011 (and its hexadecimal value is 0xBB). The binary value of decimal 242 is 1111 0010 (and its hexadecimal value is 0xF2). Let’s compare these two values bit by bit, using the bitwise AND operator:

N1 N2 N1 & N2

1 1 1

0 1 0

1 1 1

Binary 1 1 1 0 1 0

0 0 0

1 1 1

1 0 0

Decimal 187 242 178

Most of the times, you will want the interpreter to perform this operation and use the result in your program. This means that you can get the result of this operation and possibly display it to the user. The above operation can be performed by the following program: PRINT 187 & 242 This would produce 178

Bits Comparison: The Bitwise OR Operator | You can perform another type of comparison on bits using the bitwise OR operator that is represented by |. Its syntax is: Value1 | Value2 Once again, the interpreter compares the corresponding bits of each operand. If at least one of the equivalent bits is 1, the comparison produces 1. The comparison produces 0 only if both bits are 0. This operation is resumed as follows:

Bit1 0 1 0 1

Bit2 0 0 1 1

Bit1 | Bit2 0 1 1 1

Once again, let’s consider decimals 187 and 242. Their bitwise OR comparison would render the following result:

N1 N2 N1 | N2

1 1 1

0 1 1

1 1 1

Binary 1 1 1 0 1 1

0 0 0

1 1 1

1 0 1

Decimal 187 242 251

You can also let the compiler perform the operation and produce a result. Here is an example: PRINT 187 | 242 This would produce 251

Bits Comparison: The Bitwise-Exclusive XOR Operator ^ Like the previous two operators, the bitwise-exclusive OR operator performs a bit comparison of two values. It syntax is: Value1 ^ Value2 The compiler compares the bit of one value to the corresponding bit of the other value. If one of the bits is 0 and the other is 1, the comparison produces 1. In the other two cases, that is, if both bits have the same value, the comparison produces 0. This operation is resumed as follows:

Bit1 0 1 0 1

Bit2 0 0 1 1

Bit1 ^ Bit2 0 1 1 0

We will again consider decimals 187 and 242. Their bitwise-exclusive XOR comparison would render the following result:

N1 N2 N1 ^ N2

1 1 0

0 1 1

1 1 0

Binary 1 1 1 0 0 1

0 0 0

1 1 0

1 0 1

Decimal 187 242 73

If the interpreter performs this operation, it can produce a result as in the following example: PRINT 187 ^ 242; This would produce 73.

Declaring Variables DECLARE Options

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 underscores, letters, and 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

DECLARE @VariableName DataType; DECLARE @Variable1 DataType1, @Variable2 DataType2, @Variable_n DataType_n;

Initializing a Variable SELECT @VariableName = DesiredValue or SET @VariableName = DesiredValue

Data Types Introduction

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

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 declare a variable that holds a Boolean value, you can use the BIT or bit keyword. Here is an example: DECLARE @IsOrganDonor bit;

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

Integer Variables An integer, also called a natural number, or a whole number, is a number that can start with a + or a - sign and is made of digits. Between the digits, no character other than a digit is allowed. In the real world, when a number is (very) long and becomes difficult to ready, such as 79435794, you are allowed to type a symbol called the thousand separator in each thousand increment. An example is 79,435,794. In your SQL expressions, never include the thousand separator: you would receive an error. DECLARE @Category int SET @Category = 208 PRINT @Category GO 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 newspaper, apply the tinyint data type to such a field. A variable with the tinyint data type can hold positive numbers that range from 0 to 255. Here is an example: 1> DECLARE @StudentAge tinyint; 2> SET @StudentAge = 14; 3> SELECT @StudentAge AS [Student's Age]; 4> GO Student's Age ------------14

(1 rows affected) The smallint data type follows the same rules and principles as the int data type except that it is used to store smaller 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 its field can hold 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 hexadecimal numbers are 0x7238, 0xFA36, or 0xAA48D. Use the binary data type if all values of the variable would have the exact same length (or quantity). If you anticipate that some entries would be different than others, then use the alternative varbinary data type. The varbinary type also is used for hexadecimal numbers but allows dissimilar entries, as long as all entries are hexadecimals.

Practical Learning: Using Integer Variables 1. Change the statement as follows: DECLARE @IsMarried bit, @EmplStatus int; SET @IsMarried = 1; SET @EmplStatus = 2; SELECT @IsMarried AS [Is Married?], @EmplStatus AS [Employment Status]; GO

Decimal Variables A decimal number is a number that can have a period (or the character used as the decimal separator as set in the Control Panel) between the digits. An example would be 12.625 or 44.80. Like an integer, a decimal number can start with a + or just a digit, which would make it a positive number. A decimal number can also start with a - symbol, which would make it a negative number. If the number

represents a fraction, a period between the digits specifies what portion of 1 was cut. If you anticipate such a number for a field, specify its data type as numeric or decimal (either decimal or 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

Currency Variables

If a variable would hold monetary values, you can declare it with the money keyword. A variable with a money data type can hold positive or negative values from -922,337,203,685,477.5808 to +922,337,203,685,477.5807. Here is an 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)

Date and Time Variables A DATETIME data type is used for a column whose data would consist of date and/or time values. The entries must be valid date or time values but Microsoft SQL Server allows a lot of flexibility, even to display a date in a non-traditional format. The date value of a datetime field can be comprised between January 1st, 1753 and December 31, 9999. 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

Practical Learning: Using Date/Time Variables 1. Change the statement as follows: 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

Character Variables A field of characters can consist of any kinds of alphabetical symbols in any combination, readable or not. If you want a variable to hold a fixed number of characters, such as the book shelf numbers of a library, declare it with the char data 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. After declaring the variable, when initializing it, include its value in single-quotes. Here is an example: 1> DECLARE @Gender char; 2> SET @GENDER = 'M'; 3> SELECT @Gender AS Gender; 4> GO Gender -----M (1 rows affected)

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'; 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

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

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

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

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

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

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

Conditional Statements

BEGIN...END To indicate that your Statement covers more than one line, start it with the BEGIN keyword. Then you must use the END keyword to indicate where the Statement ends. In this case, the formula of a conditional statement would appear as follows: Keyword Expression BEGIN Statement Line 1 Statement Line 2 END

Statement Line n

IF a Condition is True IF Condition Statement When creating an IF statement, first make sure you provide a Condition expression that can be evaluated to produce true or false. To create this Condition, you can use variables and the logical comparison operator reviewed above. When the interpreter executes this statement, it first examines the Condition to evaluate it to a true result. If the Condition 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

IF...ELSE The IF condition we used above is appropriate when you only need to know if an expression is true. There is nothing to do 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

CASE...WHEN...THEN The CASE keyword is used as a conditional operator that considers a value, examines it, and acts on an option depending 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 created as Male. If 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 WHEN 'M' THEN WHEN 'f' THEN WHEN 'F' THEN END;

'Male' 'Male' 'Female' 'Female'

SELECT 'Student Gender: ' + @Gender; GO

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

In most cases, you may know the only types of value that would be submitted to a CASE statement. In some other cases, an unpredictable value may be submitted. If you anticipate a value other than those you are aware of, the CASE statement provides a "fit-all' alternative by using the last statement as ELSE. In this case, the formula of the CASE statement would be: CASE Expression 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 example: 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

WHILE To examine a condition and evaluate it before taking action, you can use the WHILE operator. The basic formula of this statement is: WHILE Expression Statement Here is an example: DECLARE @Number As int WHILE @Number < 5 SELECT @Number AS Number GO

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

The TRUE and FALSE Constants In Boolean algebra, something is considered TRUE when it holds a value. The value is also considered as 1 or Yes. By contrast, if something doesn't hold a value, it is considered non-existent and non-worthy of consideration. Such a thing has a value of FALSE, 0, or No. To retrieve such a value, you can just find out if the value of a field is existent or not. The comparison for a True or False value is mostly performed on Boolean fields, such a case is the SPHome (which specifies whether a student lives in a single parent home) field of the Students table of the HighSchool database. If a record has a value of 1, the table considers that such a field is True. If the field has a 0 value, then it holds a FALSE value.

The NULL Constant After you have declared a variable, the SQL interpreter reserves a space in the computer memory for it but doesn't put anything in that memory space. At that time, that area of memory doesn't hold a significant value. Also at that time, the 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 is 0. It doesn't even mean that the variable's memory space is empty. It actually means that we cannot clearly determine the current value that the variable is holding.

To support the null value, Transact-SQL provides a constant named NULL. The NULL constant is mostly used for 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 that something is 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

The NOT Operator To deny the presence, the availability, or the existence of a value, you can use the NOT operator. This operator is primarily used to reverse a Boolean value. For example, we have learned that FALSE is the opposite of TRUE. In the same way, TRUE is the opposite of FALSE. If you want to compare a value as not being TRUE, the NOT TRUE would produce the same result as the FALSE value. For the same reason, the expression NOT FALSE is the same as TRUE.

Introduction to Functions

CREATE FUNCTION FunctionName()

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 or a value. When creating a function, you must specify the type of value that the function would return. To provide this information, after the name of the function, type the RETURNS keyword followed by a definition for a data type. Here is a simple example: CREATE FUNCTION Addition() RETURNS Decimal(6,3)

After specifying the type of value that the function would return, you can create a body for the function. The body of a function starts with the BEGIN and ends with the END keywords. Here is an example:

CREATE FUNCTION Addition() RETURNS Decimal(6,3) BEGIN END Optionally, you can type the AS keyword before the BEGIN keyword: CREATE FUNCTION Addition() RETURNS Decimal(6,3) AS BEGIN END Here is an example CREATE FUNCTION GetFullName() RETURNS varchar(100) AS BEGIN RETURN 'Doe, John' END

Function Calling After a function has been created, you can use the value it returns. Using a function is also referred to as calling it. To call a function, you must qualify its name. To do this, type the name of the database in which it was created, followed by the period operator, followed by dbo, followed by the period operator, followed by the name of the function, and its 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 either PRINT or SELECT to display the function's value in a query window. Here is an example that calls the above Addition() function: PRINT Exercise.dbo.GetFullName(); 1. To execute the function we just created, execute the following statement: PRINT RealEstate1.dbo.CalculateWeeklySalary(); GO 1. To specify a column name for the returned value of a function, change the function as follows and execute it: SELECT RealEstate1.dbo.CalculateWeeklySalary() AS [Weekly Salary]; GO 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: CREATE FUNCTION 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

Function Arguments Introduction In order to carry its assignment, a function can be provided with some values. Put it another way, when you create a function, instead of, or in addition to, local variables, you may want the code that will call the function to provide the values needed to perform the assignment. For example, imagine you want to create a function that would generate employees email addresses when a user has entered a first and last name. At the time you are creating the function, you cannot know or predict the names of employees, including those who have not even been hired yet. In this case, you can write the whole function but provide one or more placeholders for values that would be supplied when the function is called. An external value that is can also take more than you also decide whether what those parameters, if

provided to a function is called a parameter. A function one parameter. Therefore, when you create a function, your function would take one or more parameters and 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 use an external value, its parentheses can be left empty. If a function will use an external value, when you create the function, you must specify a name and the type of value of the parameters. The name of the parameter is created with the @ sign, like a variable as we saw in the previous lesson. Here is an example: CREATE FUNCTION Addition(@Number1 Decimal(6,2))

When a function takes a parameter, in the body of the function, you can use the parameter as if you knew its value, as 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 do this, type the 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 this case, separate 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 value. You can also 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 a value for each 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 calls the above 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:

Practical Learning: Creating Functions With Arguments 1. In the Object Explorer, under the Scalar-Valued Functions node, right-click dbo.CalculateWeeklySalary and click 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 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], LockmanRealEstate.dbo.CalculateWeeklySalary(@Hours, @Hourly) AS [Weekly Salary]; GO

6. Press F5 to execute the statement

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

Built-In Functions Fundamentals Casting a Value In most cases, a value the user submits to your database is primarily considered a string. This is convenient if that's what you are expecting. If the value the user

provides must be treated as something other than a string, for example, if the user provides a number, before using such a value, you should first convert it to the appropriate type, that is, from a string to the expected type. To assist with conversion, you can use either the CAST() or the CONVERT() function. The syntax of the CAST() 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 want to convert the 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 be involved in a 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

Converting a Value Like CAST(), the CONVERT() function is used to convert a value. Unlike CAST(), CONVERT can be used to convert a value its original type into a non-similar type. For example, you can use CONVERT to cast a number into a string and 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 converting the value into a string (varchar, nvarchar, char, nchar) or a binary type, you should specify the number of allowed characters the data type's own parentheses. As reviewed for the CAST() function, the Expression is the value that needs to be converted. 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; PRINT 'Square Characteristics'; PRINT '-----------------------'; PRINT 'Side = ' + CONVERT(varchar(10), @Side, 10); PRINT 'Perimeter = ' + CONVERT(varchar(10), @Perimeter, 10);

PRINT 'Area GO

= ' + CONVERT(varchar(10), @Area, 10);

The Length of a String int LEN(String) This function takes one argument as the string to be considered. It returns the number of characters in the string. Here is an example: DECLARE @FIFA varchar(120) SET @FIFA = 'Fédération Internationale de Football Association' SELECT @FIFA AS FIFA SELECT LEN(@FIFA) AS [Number of Characters]

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 ASCII values. If you have a string, to get the ASCII code of its leftmost character, you can use the ASCII() function. Its syntax is: int ASCII(String) This function takes as argument as string and returns the ASCII code of the first (the left) character of the string. Here is an example: DECLARE @ES varchar(100) SET @ES = 'El Salvador' SELECT @ES AS ES SELECT ASCII(@ES) AS [In ASCII Format]

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 CHAR() function. Its syntax is: char CHAR(int value) This function takes as argument a numeric value as an integer. Upon conversion, the function returns the ASCII 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 particular case. When you receive a string, if you want to convert all of its characters to lowercase, you can use the LOWER() function. 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. Any letter that is part of the string would be converted to lowercase. Any other character or symbol would be kept "as is". After conversion, the LOWER() function returns a new string.

Here is an example: DECLARE @FIFA varchar(120) SET @FIFA = 'Fédération Internationale de Football Association' SELECT @FIFA AS FIFA SELECT LOWER(@FIFA) AS Converted

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 for any necessary reason. A left sub-string is one or a group of characters retrieved from the left side of a known string. To get the left sub-string 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 argument specifies the number of characters from the most-left that will constitute the sub-string. After the operation, the LEFT() function 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

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 characters of an 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 argument specifies the number of characters from the most-right that will constitute the sub-string.

Practical Learning: Getting the Right Characters

-- ============================================= -- Function: Last4DigitsOfSSN -- ============================================= CREATE FUNCTION Last4DigitsOfSSN(@SSN varchar(12)) RETURNS char(4) AS BEGIN RETURN RIGHT(@SSN, 4); END GO

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 contains unexpected characters. This could be due to its formatting or any other reason. For example, if you request a telephone number from a user, there are various ways the string could be presented to you. Examples are 000000-0000, or 0000000000, or (000) 000-0000. Every one of these formats is an acceptable US and Canadian telephone number but if you involve that string in an operation, you could get an unpredictable result. One way you can solve this type of problem is to remove any undesired characters from the string. This operation can also consist of replacing some character(s) with other(s). To replace one character or a sub-string from a string, you can use the REPLACE() function. Its syntax is: 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 second argument, FindString, is a character or a sub-string to look for in the String argument. If the FindString character or sub-string is found in the String, then it is replaced with the value of the last argument, ReplaceWith.

Practical Learning: Replacing Characters or Sub-Strings -- ============================================= -- 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

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 (higher than 0). When a number is negative, it must have a symbol to its left. If it is positive, it may display a + symbol to its left or it can omit it. A number without the - or + symbol to its left is considered positive, also referred to as unsigned. The symbol that determines whether a number is positive or negative is referred to as its sign. The sign is easily verifiable if you know the number already. In some cases, when a number is submitted to your application, before taking any action, you 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 is: SIGN(Expression) This function takes as argument a number or an expression that can be evaluated to a number. The interpreter would 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



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



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

The Absolute Value of a Number The decimal numeric system counts from minus infinity to infinity. This means that numbers are usually negative or positive, depending on their position from 0, which is considered as neutral. In some operations, the number considered will need to be only positive even if it is provided in a negative format. The absolute value of a number x is x if the number is (already) positive. If the number is negative, its absolute value is its positive equivalent. For example, the 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: ABS(Expression) This function takes an expression or a number as argument and returns its absolute value. Here is an example: DECLARE @NumberOfStudents INTEGER; SET @NumberOfStudents = -32; SELECT ABS(@NumberOfStudents) AS [Number of Students]; GO

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 and –25, with –24 being greater. In algebra, the ceiling of a number is the closest integer that is greater than or higher than the number considered. In the first case, the ceiling of 12.155 is 13 because 13 is the closest integer greater than or equal to 12.155. The ceiling of – 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 conversion, if the function succeeds, it returns a double-precision number that is greater than or equal to Expression. Here is an example:

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: 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 with 128 being the lower. The number –36.72 is between – 37 and –36 with –37 being the lower. The lowest but closest integer value of 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: FLOOR(Expression) The FLOOR() function takes as argument a numeric value or an expression that can be evaluated to a number. If the function succeeds during its conversion, it produces the integer that is the floor of the argument. Here is an example: 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 To calculate the exponential value of a number, Transact-SQL provides the EXP() function. Its syntax is: EXP(Expression) This function takes one argument as a number or an expression that can be evaluated to a number. Here is an example: 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 using the following 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 evaluated. The second argument, y, also called the exponent, will raise x to this value. Here is an example: 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 To assist with finding the natural logarithm of a number, Transact-SQL provides the LOG() function. Its syntax is: LOG(Expression) This function takes one argument as a number or an expression that can evaluate to a number. After the calculation, it 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:

The Base-10 Logarithm of a Number To calculate the base 10 logarithm of a number, Transact-SQL provides the LOG10() function. Its syntax is: LOG10(Expression) The number to be evaluated is passed as the argument X. The function returns the logarithm on base 10 using the 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:

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 calculation, 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:

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

In this case, you can use a control statement to find out whether the Expression is positive. Here is an example: 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:

Here is another example of executing the statement:

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

Radians RADIANS(Expression)

Degrees

If you know the radians but want to get the degrees of an angle, you can use the DEGREES() function. Its syntax is: DEGREES(Expression) This function takes as argument a value in radians. If it succeeds, it returns the equivalent value in degrees.

Trigonometric Functions 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 and returns its cosine. Here is an example: DECLARE @Angle As Decimal(6, 3); SET @Angle = 270; SELECT COS(@Angle) AS [Cosine of 270];

The Sine of a Value 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 sine of the angle between –1 and 1. Here is an example: DECLARE @Angle As Decimal(6, 3); SET @Angle = 270; SELECT SIN(@Angle) AS [Sine of 270]; GO

The Tangent of a Value TAN(Expression) Here is an example: DECLARE @Angle As Decimal(6, 3); SET @Angle = 270; SELECT TAN(@Angle) AS [Tangent of 270]; GO

Date and Time Based Functions Introduction Date and time values are highly used in database applications. They involve sales, time sheets, taxes, overtime work, etc. Based on this usefulness, their operations are supported by various libraries you will be using when developing your application. Without being the most elaborate on this issue, Transact-SQL provides its own level of support for date and time values. Before using a date or a time value in a calculation, remember that you must first get it one way or another. You can define a date or a time constant in your application. An example would be '1992/10/28'. You can declare a DateTime or a SmallDateTime variable and initialize it as you see fit. You may get a date or a

time from another function. As the last alternative, you may get a date or time from another application or from a user. Once you have an appropriate date, you 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. For example, if you create a time sheet, when the user starts using it, it would be convenient to fill part of the time sheet with such predictable values. To get the current date and the current time of the computer that a user is using, you can use the GETDATE() function 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 adding a value to it. 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 performed. It can be a 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 floating point value, such as 4.06. When calling this function, you must first specify the type of value that you want to add. This type is passed as the first 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 (remember that 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



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



If you want to add a number of months to a date, specify the TypeOfValue as Month or m, or mm. The following 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

In the same way, you can add values as follows: Type of Value Year quarter Month dayofyear Day Week Hour

Abbreviation yy yyyy q qq m mm y dy d dd wk ww hh

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

minute second millisecond

n mi s ss ms

A number of minutes will be added to the time value 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 that has elapsed in the range of two dates or two time values. To support this operation, Transact-SQL provides the DATEDIFF() function. Its syntax is: DATEDIFF(TypeOfValue, StartDate, EndDate) This function takes three arguments. The second argument is the starting date or the starting time of the range to be considered. The third argument is the end or last date or time of the considered range. You use the first argument to specify the type of value you want the function to produce. This argument uses the same value as those of the 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: 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:

The Tables of a Database Tables Names To complete the creation of a table, you must save it. If you are freshly creating a table and decide to save it, you would be prompted to name it. The name of a table: •

Can be made of digits only. For example you can have a table called 148



Can start with a digit, a letter, or an underscore



Can be made of letters, digits, and spaces

Creating a Table With SQL Introduction In SQL, to create a table, you start with the following statement: CREATE TABLE TableName;

Renaming a Table If you find out that the name of a table is not appropriate, you can change it. To change the name of a table in the SQL Server Management Studio, in the Object Explorer, right-click the table and click Rename. Type the desired name and press Enter. To change the name of a table with code, execute sp_rename, followed by the current name of the table, a comma, and the new desired name of the table. The formula to use is: sp_rename ExistingTableName, TableNewName; The names of tables should be included in single-quotes. Here is an example: sp_rename 'StaffMembers', 'Employees'; GO

Deleting a Table If you have an undesired table in a database, you can remove it. To delete a table in the SQL Server Management Studio, in the Object Explorer, right-click the table under its database node and click Delete. You will receive a warning giving you a chance to confirm your intentions. If you still want to remove the table, click OK. To delete a table using SQL, use the following formula: DROP TABLE TableName

Programmatic Creation of Columns CREATE TABLE <schema_name, sysname, dbo>. ( column1 int, column2 char(10) ) Example 1. CREATE TABLE Customers (

DrvLicNbr VarChar(50), DateIssued DateTime, DateExpired DateTime, FullName varchar(120), Address VARCHAR(120), City varchar(50), State varchar(100), PostalCode varchar(20), HomePhone varchar(20), OrganDonor bit) GO

Modifying a Column ALTER TABLE TableName

Adding a New Column ALTER TABLE TableName ADD ColumnName Properties The ColumnName factor is required. In fact, on the right side of the ADD keyword, define the column by its name and using all the options we reviewed for columns. Here is an example: ALTER TABLE StaffMembers ADD Address varchar(100) NULL GO

Renaming a Column If you find out that the name of a column is not appropriate, you can change it. To rename a column in the Object Explorer, right-click the table that the column belongs to and click Modify. In the design view, highlight the name of the desired column to put it into edit mode and edit it. In SQL, to change the name of 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. Here is an example: sp_rename 'StaffMembers.FullName', 'EmployeeName', 'COLUMN' GO

When this code is executed, the interpreter will look for a column named FullName in the StaffMembers table of the current or selected database. If it finds that column in the table, then it renames it EmployeeName

Deleting a Column ALTER TABLE TableName DROP COLUMN ColumnName

Data Entry INSERT TableName VALUES(Column1, Column2, Column_n); Alternatively, or to be more precise, you can use the INTO keyword between the INSERT keyword and the TableName factor to specify that you are entering data in the table. This is done with the following syntax: INSERT INTO TableName VALUES(Column1, Column2, Column_n) INSERT INTO Countries VALUES('Angola', 1246700, 12127071, 'Luanda','ao');

The Nullity of a Field NULL or NOT NULL? If creating a table using SQL, to specify that it can allow null values, type NULL on the right side of the column. To specify that the values of the column are required, on the right side, type NOT NULL. If you don't specify NULL or NOT NULL, the column will be created as NULL. Here are examples: CREATE TABLE Persons ( FirstName varchar(20) NULL, LastName varchar(20) NOT NULL, Gender smallint ); GO

Identity Columns Introduction One of the goals of a good table is to be able to uniquely identity each record. In most cases, the database engine should not confuse two records. Consider the following table: Category Item Name

Size

Women

Large 39.95

Long-sleeve jersey dress

Unit Price

Boys

Iron-Free Pleated Khaki Pants

S

39.95

Men

Striped long-sleeve shirt

Large 59.60

Women

Long-sleeve jersey dress

Large 45.95

Girls

Shoulder handbag

Women

Continental skirt

45.00 Petite 39.95

Imagine that you want to change the value of an item named Long-sleeve jersey dress. Because you must find the item programmatically, you can start looking for an item with that name. This table happens to have two items with that name. You may then decide to look for an item using its category. In the Category column, there are too many items named Women. In the same way, there are too many records that have a Large value in the Size column, same thing problem in the Unit Price column. This means that you don't have a good criterion you can use to isolate the record whose Item Name is Long-sleeve shirt. To solve the problem of uniquely identifying a record, you can create a particular column whose main purpose is to distinguish one record from another. To assist you with this, the SQL allows you to create a column whose data type is an integer type but the user doesn't have to enter data for that column. A value would automatically be entered into the field when a new record is created. This type of column is called an identity column. You cannot create an identity column one an existing table, only on a new table.

Creating an Identity Column Using SQL If you are programmatically creating a column, to indicate that it would be used as an identity column after its name and data type, type identity followed by parentheses. Between the parentheses, enter the seed value, followed by a comma, followed by the increment value. Here is an example: CREATE TABLE StoreItems( ItemID int IDENTITY(1, 1) NOT NULL, Category varchar(50), [Item Name] varchar(100) NOT NULL, Size varchar(20), [Unit Price] money); GO

Functions and Data Entry CREATE TABLE RepairOrders ( RepairID int Identity(1,1) NOT NULL, CustomerName varchar(50), CustomerPhone varchar(20), RepairDate DateTime ); GO When performing data entry for this table, you can let the user enter the customer name and phone number. On the other hand, you can assist the user by

programmatically entering the current date. To do this, you would call the GETDATE() function. Here are examples: INSERT INTO RepairOrders(CustomerName, CustomerPhone, RepairDate) VALUES('Annette Berceau', '301-988-4615', GETDATE()); GO INSERT INTO RepairOrders(CustomerPhone, CustomerName, RepairDate) VALUES('(240) 601-3795', 'Paulino Santiago', GETDATE()); GO INSERT INTO RepairOrders(CustomerName, RepairDate, CustomerPhone) VALUES('Alicia Katts', GETDATE(), '(301) 527-3095'); GO INSERT INTO RepairOrders(RepairDate, CustomerPhone, CustomerName) VALUES(GETDATE(), '703-927-4002', 'Bertrand Nguyen'); GO

Using Expressions For Data Entry Creating a SQL Expression You can also create an expression in SQL expression you are using to create a table. To do this, in the placeholder of the column, enter the name of the column, followed by AS, and followed by the desired expression. Here is an example: CREATE TABLE Circle ( CircleID int identity(1,1) NOT NULL, Radius decimal(8, 3) NOT NULL, Area AS Radius *Radius * PI() ); GO

Using an Expression During Data Entry When performing data entry, you must not provide a value for a column that has an expression; the SQL interpreter would provide the value automatically. Here is an example of entering data for the above Circle table: INSERT INTO Circle(Radius) VALUES(46.82); GO INSERT INTO Circle(Radius) VALUES(8.15); GO INSERT INTO Circle(Radius) VALUES(122.57); GO

Updating a Record UPDATE TableName SET ColumnName = Expression

Updating all Records USE VideoCollection; GO

UPDATE Videos SET Rating = 'R'; GO

Editing a Record UPDATE TableName SET ColumnName = Expression WHERE Condition(s) UPDATE Videos SET YearReleased = 1996 WHERE Director = 'Rob Reiner';

Removing all Records

If you think all records of a particular table are, or have become, useless, you can clear the whole table, which would still keep its structure. To delete all records from a table, first select all of them, and press Delete. You would receive a warning: Using SQL, to clear a table of all records, use the DELETE operator with the following formula: DELETE TableName;

Removing a Record DELETE FROM TableName WHERE Condition(s) DELETE FROM Videos WHERE VideoTitle = 'The Lady Killers';

Field Selection SELECT What FROM WhatObject SELECT * FROM Students; You can also qualify the * selector by preceding it with the name of the table followed by the period operator. The above statement is equivalent to: SELECT Students.* FROM Students; In Lesson 8, we saw that you could create an alias for a table by preceding a column with a letter or a word and a period operator, and then entering the name of the table followed by that letter or word. Using this feature, the above statement can be written as:

SELECT std.* FROM Students std; SELECT Students.LastName FROM Students;

Using an Alias Name for a Column Introduction In your SELECT statement, after specifying the column(s) as we have done so far, when you execute the SQL statement, the name of each column would appear as the column header. Fortunately, you can display any string of your choice for a column header. To specify a column header other than the name of the column, if you are using the Table window, type the desired string in the Alias column corresponding to the column. Here is an example:

If you are using a query window or if you are writing your SELECT statement, on the right side of the column name, type AS followed by the desired name of the column header. If the desired column header is in one word, you can simply type it. Here is an example: SELECT FirstName, LastName, HomePhone AS PhoneNumber, ParentsNames AS NamesOfParents FROM Students; GO If you want the column header to appear with more than one word, you can provide the words as a string in single-quotes or between the square brackets: [ and ] . Here is an example: SELECT FirstName AS [First Name], LastName AS [Last Name], HomePhone AS [Phone Number], ParentsNames AS [Names of Parents] FROM Students; GO

By qualifying each column, the above statement can also be written as follows: SELECT Students.FirstName AS [First Name], Students.LastName AS [Last Name], Students.HomePhone AS [Phone Number], Students.ParentsNames AS [Names of Parents] FROM Students; GO It can also be written as follows:

SELECT dbo.Students.FirstName AS [First Name], dbo.Students.LastName AS [Last Name], dbo.Students.HomePhone AS [Phone Number], dbo.Students.ParentsNames AS [Names of Parents] FROM Students; GO It can also be written as follows: SELECT std.FirstName AS [First Name], std.LastName AS [Last Name], std.HomePhone AS [Phone Number], std.ParentsNames AS [Names of Parents] FROM Students std; GO

Practical Learning: Using Alias Names 1. To use the alias names of columns, change the statement as follows: SELECT house.PropertyNumber AS [Prop #], house.ZIPCode AS [Location], house.YearBuilt AS [Year Built], house.PropertyType AS [Type], house.Bedrooms AS [Beds], house.Bathrooms AS [Baths], house.MarketValue AS [Value] FROM Properties house; GO

A Combination or Expression of Columns Using the SELECT keyword, we have learned to create a list of isolated columns. These columns were rendered separate of each other. Instead of having separate columns, you can combine them to create a string or a value that is in fact an expression. For example, you can combine a first name and a last name to produce a full name as an expression. Another expression can use a date on the table, add a number to it to get a date on another day. An expression can also be used to perform a calculation on two or more columns such as employees weekly hours multiplied by their hourly salary to get their weekly salary. The most common operator used is the addition. It can be used to combine two or more strings to get a new one. Here is an example: SELECT FirstName + ' ' + LastName FROM Students; GO SELECT WeeklyHours * HourlySalary FROM Payroll You can also create an alias for an expression to give it the desired name. To do this, on the right side of the expression, type AS followed by the name. AS we learned earlier, if the alias is in more than one word, include it in either single quotes or square brackets. Here is an example: SELECT FirstName + ' ' + LastName AS 'Full Name', EmrgName + ' ' + EmrgPhone AS [Emergency Contact]

FROM GO

Students;

This would produce:

The Assignment Operator If you just create a regular expression using arithmetic operators, the new column would not have a name. The SQL allows you to specify a different name for any column during data analysis or a name for an expression. This is done using the assignment operator "=". To change the name of a column during data analysis, on the right side of SELECT, type the desired name, followed by the assignment operator, followed by the actual name of the column. Here is an example: SELECT EmergencyName = EmrgName FROM Students; GO

If you want to use more than one column, type each and assign it the desired name, separate them with commas. Here is an example: SELECT LastName, EmergencyName = EmrgName, EmergencyPhone = EmrgPhone FROM Students; GO This would produce:

You can also include the name between single-quotes or the square brackets. Here are examples: SELECT LastName + ', ' + FirstName AS [Full Name], [Emergency Name] = EmrgName, 'Emergency Phone' = EmrgPhone FROM Students; GO

This would produce:

Sorting the Records SELECT What FROM WhatObject ORDER BY WhatField; The column used as the basis must be recognized as part of the selected columns. For example, to get a list of students in alphabetical order based on the LastName column, you can use the following statement: SELECT FirstName, LastName, Gender, ParentsNames, SPHome FROM Students

ORDER BY LastName; GO SELECT What FROM WhatObject ORDER BY WhatField; The column used as the basis must be recognized as part of the selected columns. For example, to get a list of students in alphabetical order based on the LastName column, you can use the following statement: SELECT FirstName, LastName, Gender, ParentsNames, SPHome FROM Students ORDER BY LastName; GO By default, records are ordered in ascending order. Nevertheless, the ascending order is controlled using the ASC keyword specified after the based field. For example, to sort the last names in ascending order including the first and last names, you would use a statement as follows: SELECT * FROM Students ORDER BY LastName ASC On the other hand, if you want to sort records in reverse order, you can use the DESC keywords instead. It produces the opposite result to the ASC effect. Here is an example: SELECT FirstName, LastName, Gender, ParentsNames, SPHome FROM Students ORDER BY LastName DESC; GO

Operators and Data Analysis WHERE is the Condition SELECT DateOfBirth, LastName, FirstName, Gender, State, ParentsNames FROM Students WHERE State='MD' ORDER BY LastName;

Logical Conjunctions SELECT WhatColumn(s) FROM WhatObject WHERE Condition1 AND Condition2 SELECT FirstName, LastName, Gender, City, State

FROM WHERE

Students Gender = 'female' AND State = 'md';

IN a Selected Series If you have a series of records and you want to find a record or a group of records among them, you can use the IN operator by adding it to a WHERE statement. The IN operator is a type of various OR operators. It follows this formula: IN(Expression1, Expression2, Expression_n) Each Expression factor can be one of the values of a column. This is equivalent to Expression1 OR Expression2 OR Expression_n, etc. From our list of students, imagine that you want to get a list of students who live either in Silver Spring, in Rockville, or in Chevy Chase. You can write an IN expression as follows: SELECT FirstName, LastName, Gender, City, State, ZIPCode, SPHome FROM Students WHERE City IN ('silver spring', 'rockville', 'chevy chase');

Practical Learning: Stepping IN 1. To get a list of single family and townhouses, change the statement as follows: SELECT house.PropertyNumber AS [Prop #], house.PropertyType AS Type, house.YearBuilt AS [Year Built], house.City, house.State, house.ZIPCode AS [ZIP Code], house.Bedrooms AS Beds, house.Bathrooms AS Baths, house.MarketValue AS Value FROM Properties house WHERE house.PropertyType IN ('Single Family', 'Townhouse'); GO

Pattern Operator: LIKE Introduction Most or all of the criteria we have specified with the WHERE keyword had to exactly match the specified criterion. In some cases, you may not remember the exact value of records but you want to specify some type of approximation. To do this, you use the LIKE operator.

If you are visually creating the statement, in the Table window, click the Criteria box corresponding to the column on which the condition would be applied and type. In a SQL statement, the LIKE operator is used in a formula as follows: Expression LIKE pattern The pattern factor can be a value to be found in Expression. For example, it can be the same type of value used in a WHERE statement. In this case, the equality operator would be the same as LIKE. For example SELECT DateOfBirth, LastName, FirstName, Gender, State, ParentsNames FROM Students WHERE State = 'VA'; GO is equivalent to SELECT DateOfBirth, LastName, FirstName, Gender, State, ParentsNames FROM Students WHERE State LIKE 'VA'; GO The idea of using a LIKE operator is to give an approximation of the type of result you want. There are wildcards to use with the LIKE operator.

LIKE Any Character % If you want to match any character, in any combination, for any length, use the % wildcard. If you precede it with a letter, as in S%, the condition would consist of finding any string that starts with S. Imagine that you want to get a list of students whose last names start with S. You would type the condition as LIKE 'S%'. To do this visually, in the Criteria section, under the Filter column, type the condition. Here is an example: The SQL statement is this query is: SELECT FROM WHERE

FirstName, LastName, Gender, SPHome Students (LastName LIKE 'S%')

You can negate this condition by preceding it with NOT. Here is an example: SELECT FROM WHERE

FirstName, LastName, Gender, SPHome Students (NOT (LastName LIKE 'S%'))

This time, the result is the list of students whose last names don't start with S.

When you precede the % character with a letter, only that letter would be considered. Alternatively, you can specify a group of characters that would precede the % symbol. For example, if you have some first names that start with Ch in a list but you don't remember the end of the name you are looking for, to create the list, you can specify that the first name would start with Ch and end with whatever. In this case, you would use Ch% as follows: SELECT FROM WHERE

FirstName, LastName, Gender, SPHome Students (LastName LIKE 'Ch%')

Instead of ending a letter or a group of letters with %, you can begin the LIKE statement with %. An example would be LIKE "%son". In this case, all strings that end with son, such as Johnson or Colson, would be considered. If you remember neither the beginning nor the end of a string you want to search for, but you know a sub-string that is probably included in the type of string you are looking for, you can precede it with % and end it with %. An example would be LIKE "%an%". In this case, all strings that include "an" anywhere inside would be considered. Here is an example: SELECT FROM WHERE

FirstName, LastName, Gender, SPHome Students (LastName LIKE '%an%')

LIKE a Range of Characters [] The % wildcard is used to precede or succeed a specific character or a group of characters, that is, any character. If you want to consider only a range of characters from the alphabet, you can include the range in square brackets. To do this, type [, followed by the lowest character of the range, followed by -, followed by the highest character of the range, followed by ]. For example, to consider the range of letters between p and s, you would use '[p-s]'. Then, either to the left, to the right, or to both sides of this expression, type % to specify whether to include any character or combination of characters before or after the expression. Here is an example: SELECT FROM WHERE

FirstName, LastName, Gender, SPHome Students (LastName LIKE '%[p-s]')

Not Ending With a Range of Characters As opposed to considering the characters that are in a specific range, to specify a character or a range of characters that must NOT be considered, use the ^ character inside the square brackets but before the desired range. Here is an example: SELECT FROM WHERE

FirstName, LastName, Gender, SPHome Students (LastName LIKE '%[^p-r]')

The result would be a list of students whose last end with a letter other than p, q, r, or s. Once again, remember that you can negate this expression by preceding it with NOT. Note that if you negate an expression that include ^, you would get the same result as not using ^.

Functions and Data Analysis Using a Built-In Function SELECT FirstName, LastName, Gender, DATEDIFF(year, DateOfBirth, GETDATE()) AS Age FROM Students; GO SELECT FirstName, LastName, Gender, DateOfBirth, SPHome FROM Students WHERE (DateOfBirth BETWEEN CONVERT(DATETIME, '1995-01-01', 102) AND CONVERT(DATETIME, '1999-12-31', 102))

Using a User-Defined Function If none of the built-in functions satisfies your needs, you can create your own and use it during data analysis. Obviously, you should first create the function. Here is an example of two functions created in the ROSH database: /* ============================================= Author: FunctionX Create date: Friday 6 April, 2007 Description: This function is used to get the full name of a student =============================================*/ CREATE FUNCTION GetFullName ( @FName varchar(20), @LName varchar(20) ) RETURNS varchar(41) AS BEGIN RETURN @LName + ', ' + @FName; END; GO /* ============================================= Author: FunctionX Create date: Saturday 7 April, 2007 Description: This function is used to display Yes or No ============================================= */ CREATE FUNCTION ShowYesOrNo (

@SPHomeStatus bit ) RETURNS varchar(3) AS BEGIN DECLARE @Result varchar(3); IF @SPHomeStatus = 0 SET @Result = 'No'; ELSE SET @Result = 'Yes'; RETURN @Result;

END; GO

Once a function is ready, in the placeholder of your SQL statement, type dbo., followed by the name of the function, its parentheses, and its paremeter(s), if any, inside of the parentheses. Here is an example: SELECT StudentID, dbo.GetFullName(FirstName, LastName) AS [Student's Name], Gender, dbo.ShowYesOrNo(SPHome) AS [Live's in a Single Parent Home?], ParentsNames AS [Parents' Names] FROM Students; GO

Relationships and Data Integrity The Primary Key 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 ); In the SQL, you can give a specific name to a primary. 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 SQL You can also create a foreign key in he 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)

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) );

Data Joins Introduction When studying relationships, we reviewed techniques of making data from one table available to the records of another table. This demonstrated to reduce data duplication and mistakes. Another issue that involves the combination of tables consists of creating records from more than one table and making the result into a single list. This is the basis of data joins. A data join is a technique of creating a list of records from more that one table, using all columns from all tables involved, or selecting only the desired columns from one or all of the tables involved. This means that a data join is essentially created in three steps: 1. The tables that will be involved in the join 2. A column that will create the link in each table

3. A SQL statement that will create the records

The Tables of a Join 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 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 FROM Persons TypeOfJoin Genders ON Persons.GenderID = Genders.GenderID

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

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.

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

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

Outer Joins 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):

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 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. 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 right-clicking 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:

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

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:

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

Practical Learning: Analyzing Data Involving Joins 1. To see a list of only townhouses, change the statement in the SQL section as follows: SELECT PropertyTypes.PropertyType, Properties.City, Properties.State, Properties.ZIPCode, Properties.Bedrooms, Properties.Bathrooms, Properties.Stories, Properties.MarketValue FROM Properties RIGHT OUTER JOIN PropertyTypes ON Properties.PropertyTypeID = PropertyTypes.PropertyTypeID WHERE (PropertyTypes.PropertyTypeID = 3)

2. On the Query Designer toolbar, click the Execute SQL button

3. To get a list of townhouses and single families, change the SQL statement as follows: SELECT PropertyTypes.PropertyType, Properties.MarketValue, Properties.City, Properties.State, Properties.Bedrooms, Properties.YearBuilt, Properties.Bathrooms, Properties.FinishedBasement, Properties.Stories FROM Properties RIGHT OUTER JOIN PropertyTypes ON Properties.PropertyTypeID = PropertyTypes.PropertyTypeID WHERE (PropertyTypes.PropertyTypeID IN (2, 3))

4. On the Query Designer toolbar, click the Execute SQL button 5. To get a list of single families arranged in chronological order starting with the newest, change the SQL statement as follows: SELECT PropertyTypes.PropertyType, Properties.City, Properties.State, Properties.ZIPCode, Properties.Bedrooms, Properties.Bathrooms, Properties.Stories, Properties.YearBuilt, Properties.MarketValue FROM Properties RIGHT OUTER JOIN PropertyTypes ON Properties.PropertyTypeID = PropertyTypes.PropertyTypeID WHERE (PropertyTypes.PropertyTypeID = 2) ORDER BY Properties.YearBuilt DESC 6. Right-click the table and click Execute SQL 7. To get a list of properties that cost between $350,000 and $425000, change the SQL statement as follows: SELECT Properties.PropertyNumber, PropertyTypes.PropertyType, Properties.MarketValue, Properties.City, Properties.State, Properties.Bedrooms, Properties.YearBuilt FROM Properties RIGHT OUTER JOIN PropertyTypes ON Properties.PropertyTypeID = PropertyTypes.PropertyTypeID WHERE (Properties.MarketValue BETWEEN 350000 AND 475000)

8. On the Query Designer toolbar, click the Execute SQL button 9. To get a list of single family homes in Virginia arranged in chronological and only if the property number is known, change the SQL statement as follows: SELECT Properties.PropertyNumber, PropertyTypes.PropertyType, Properties.MarketValue, Properties.City, Properties.State, Properties.Bedrooms, Properties.FinishedBasement, Properties.YearBuilt FROM Properties RIGHT OUTER JOIN PropertyTypes ON Properties.PropertyTypeID = PropertyTypes.PropertyTypeID WHERE (PropertyTypes.PropertyTypeID = 2) AND (Properties.PropertyNumber IS NOT NULL) AND (Properties.State = 'VA') ORDER BY Properties.YearBuilt DESC

10. On the Query Designer toolbar, click the Execute SQL button 11. To get a list of properties in southern Maryland but that cost less than $400,000, change the SQL statement as follows: SELECT Properties.PropertyNumber, PropertyTypes.PropertyType, Properties.MarketValue, Properties.City, Properties.State, Properties.Bedrooms, Properties.YearBuilt FROM Properties RIGHT OUTER JOIN PropertyTypes ON Properties.PropertyTypeID = PropertyTypes.PropertyTypeID WHERE (Properties.MarketValue < 400000) AND (Properties.ZIPCode BETWEEN '20500' AND '21000')

12. On the Query Designer toolbar, click the Execute SQL button

Views Overview of Views Introduction When studying data analysis, a query is a technique of isolating a series of columns and/or records of a table. This is usually done for the purpose of data analysis. This can also be done to create a new list of items for any particular reason. Most of the time, a query is created temporarily, such as during data analysis while using a table, a form, or a web page. After using such a temporary list, it is then dismissed. Many database applications, including Microsoft SQL Server, allow you to create a query and be able to save it for later use, or even to use it as if it were its own table. This is the idea behind a view.

Definition A view is a list of columns or a series of records retrieved from one or more existing tables, or as a combination of one or more views and one or more tables. Based on this, before creating a view, you must first decide where its columns and records would come from. Obviously the easiest view is one whose columns and records come from one table

With Transact-SQL To programmatically create a view, you use the following SQL syntax: CREATE VIEW ViewName AS SELECT Statement

Microsoft SQL Server can generate skeleton code of a view for you. To use it, first create an empty query window. Display the Template Explorer. In the Template Explorer, expand the View node. From the View node, drag Create View and drop it in the query window. The creation of a view starts with the CREATE VIEW expression followed by a name. The name of a view follows the rules and suggestions we reviewed above. After the name of the view, use the AS keyword to indicate that you are ready to define the view. Because a view is primarily a SQL statement, it is defined using a SELECT statement, using the same rules we studied for data analysis. Here is an example of a view: CREATE VIEW dbo.ListOfMen AS SELECT dbo.Genders.Gender, dbo.Persons.FirstName, dbo.Persons.LastName FROM dbo.Genders INNER JOIN dbo.Persons ON dbo.Genders.GenderID = dbo.Persons.GenderID WHERE (dbo.Genders.Gender = 'Male'); GO After creating the SQL statement that defines the view, you must execute the statement. If using a query window, you can do this by pressing F5. Once the statement is executed, its name is automatically added to the Views node of its database even if you don't save its code

Opening or Executing a View USE YugoNationalBank; GO SELECT PayrollPreparation.* FROM PayrollPreparation; GO

Modifying a View ALTER VIEW ViewName AS SELECT Statement ALTER VIEW dbo.ListOfMen AS SELECT dbo.Persons.FirstName, dbo.Persons.LastName FROM dbo.Genders INNER JOIN dbo.Persons ON dbo.Genders.GenderID = dbo.Persons.GenderID WHERE (dbo.Genders.Gender = 'Male');

Deleting a View DROP VIEW ViewName

Using a View

Data Entry With a View As seen so far, a view is a selected list of records from a table. As you may suspect, the easiest view is probably one created from one table. Imagine you have a table of employees and you want to create a view that lists only their names. You may create a view as follows: CREATE VIEW dbo.EmployeesNames AS SELECT FirstName, LastName, LastName + ', ' + FirstName AS FullName FROM Persons; GO On such a view that is based on one table, you can perform data entry, using the view, rather than the table. To do this, you follow the same rules we reviewed in Lesson 9. Here is an example: INSERT INTO dbo.EmployeesNames(FirstName, LastName) VALUES('Peter', 'Justice'); If you perform data entry using a view, the data you provide would be entered on the base table; this means that the table would be updated automatically. Based on this feature, you can create a view purposely intended to update a table so that, in the view, you would include only the columns that need to be updated.

A View With Alias Names It is important to know that a view is more of a table type than any other object. This means that a view is not a function but it can use a function. The word argument here only means that some values can be passed to a view but these values can be specified only when creating the view. They are not real arguments. When structuring a view, you can create placeholders for columns and pass them in the parentheses of the view. This would be done as follows: CREATE VIEW CarIdentifier([Tag #], Manufacturer, [Type of Car], Available) . . . If you use this technique, the names passed in the parentheses of the view are the captions that would be displayed in place of the columns of the view. This technique allows you to specify the strings of your choice for the columns. If you want a column header to display the actual name of the column, write it the same. Otherwise, you can use any string you want for the column. If the name is in one word, you can just type it. If the name includes various words, include them between an opening square bracket "[" and a closing square bracket "]". After listing the necessary strings as the captions of columns, in your SELECT statement of the view, you must use the exact same number of columns as the number of arguments of the view. In fact, each column of your SELECT statement should correspond to an argument of the same order. Here is an example: CREATE VIEW dbo.MenAndWomen([First Name], [Last Name], Gender)

AS SELECT dbo.Persons.FirstName, dbo.Persons.LastName, dbo.Genders.Gender FROM dbo.Genders INNER JOIN dbo.Persons ON dbo.Genders.GenderID = dbo.Persons.GenderID; GO

Stored Procedures Introduction In Lesson 6, we had an introduction to some types of actions that could be performed on a database. These actions were called functions. The SQL provides another type of action called a stored procedure. If you have developed applications in some other languages such as Pascal or Visual Basic, you are probably familiar with the idea of a procedure. Like a function, a stored procedure is used to perform an action on a a database

Creating a Stored Procedure CREATE PROCEDURE ProcedureName AS Body of the Procedure

Modifying a Procedure ALTER PROCEDURE ProcedureName AS Body of Procedure

Deleting a Procedure DROP PROCEDURE ProcedureName

Exploring Procedures Introduction Probably the simplest procedure you can write would consist of selecting columns from a table. This is done with the SELECT keyword and applying the techniques we reviewed for data analysis. For example, to create a stored procedure that would hold a list of students from a table named Students, you would create the procedure as follows: CREATE PROCEDURE GetStudentIdentification

AS BEGIN SELECT FirstName, LastName, DateOfBirth, Gender FROM Students END GO

Executing a Procedure To get the results of a creating a procedure, you must execute it (in other words, to use a stored procedure, you must call it). To execute a procedure, you use the EXECUTE keyword followed by the name of the procedure. Although there are some other issues related to executing a procedure, for now, we will consider that the simplest syntax to call a 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 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;

Using Expressions and Functions One of the advantages of using procedures is that not only can they produce the same expressions as we saw during analysis but also they can store such expressions to be recalled any time without having to re-write them. Based on this, you can create an expression that combines a first and a last name to produce and store a full name. Here is an example: CREATE PROCEDURE GetStudentIdentification AS BEGIN SELECT FullName = FirstName + ' ' + LastName, DateOfBirth, Gender FROM Students END GO A stored procedure can also call a function in its body. To do this, follow the same rules we reviewed for calling functions during data analysis. Here is an example of a 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

Arguments and Parameters Introduction Imagine you are creating an application for a department store that sometimes applies discounts of 10%, 20%, 40%, 55%, 70%, etc, on items it sells. Since the management decides when and what discount would be applied on an item, you cannot predict all possibilities. One way to solve this type of problem is to create a procedure that would receive the discount applied on an item and then apply this discount to the price of the item. All of the procedures we have created and used so far assumed that the values they needed were already in a table of the database. In some cases, you may need to create a procedure that involves values that are not part of the database. On such a scenario, for the procedure to carry its assignment, you would supply it with one or more values. An external value that is provided to a stored procedure is called a parameter. When you create a procedure, you must also create the parameter if you judge it necessary. When a procedure's creation is equipped with a parameter, it is said that the procedure takes an argument. A procedure can also take more than one argument. When you execute a procedure that takes one or more arguments, you must provide a value for each argument. In this case, you are said to pass a value for the argument. There are cases when you don't have to provide an argument.

Passing Arguments To create a procedure that takes an argument, type the formula CREATE PROCEDURE or CREATE PROC followed by the name of the procedure, then type the name of the argument that starts with @. The parameter is created like a column of a table. That is, a parameter must have a name, a data type and an optional length. Here is the syntax you would use: CREATE PROCEDURE ProcedureName @ParameterName DataType AS Body of the Procedure When implementing the procedure, you can define what you want to do with the parameter(s), in the body of the procedure. One way you can use a parameter is to run a query whose factor the user would provide. For example, imagine you want to create a procedure that, whenever executed, would be supplied with a gender, then it would display the list of students of that gender. Since you want the

user to specify the gender of students to display, you can create a 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 following in the 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 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 procedure that takes a parameter, make sure you provide a value for the parameter. The syntax used is: EXEC ProcedureName ParameterValue If the parameter is Boolean or numeric, make sure you provide an appropriate value. If the parameter is a character or a string, type its value in single-quotes. Here is an example: EXEC ROSH.dbo.GetListOfStudentsByGender 'Male'; Here is an example of executing it:

Notice that we could/should have omitted to include the Gender column in the statement since it would be implied to the user. Another type of procedure can be made to take more than one parameter. In this case, create the parameters in 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 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 procedure that takes more than one parameter, you must still provide a value for each parameter but you have two alternatives. The simplest technique consists of providing a value for each parameter in the exact order they appear in the procedure. Here is an example: USE ROSH; GO EXEC ROSH.dbo.IdentifyStudentsByState 'Female', 'MD'; GO This would produce:

Alternatively, you can provide the value for each parameter in the order of your choice. Consider the following procedure that takes 3 arguments: USE ROSH; GO CREATE PROCEDURE IdentifySomeStudents @Gdr varchar(20), @StateOrProvince char(2), @HomeStatus bit AS BEGIN SELECT FullName = LastName + ', ' + FirstName, DATEDIFF(year, DateOfBirth, GETDATE()) AS Age,

END GO

Gender FROM Students WHERE (Gender = @Gdr) AND (State = @StateOrProvince) AND (SPHome = @HomeStatus)

When calling this type of procedure, you can type the name of each parameter and assign it the corresponding value. 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 1. Delete the contents of the code window and, to create a stored procedure, type the following in the window: USE WattsALoan; GO EXECUTE SpecifyCurrentBalance '03/25/2004', 2, 1, 249.08;

GO EXECUTE SpecifyCurrentBalance '01/30/2006', 2, 5, 611.93; GO EXECUTE SpecifyCurrentBalance '04/20/2004', 1, 1, 249.08; GO EXECUTE SpecifyCurrentBalance '10/28/2006', 2, 4, 134.38; GO 2. To execute, press F5

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

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

ItemNumber ItemCategoryID ItemName

ItemSize UnitPrice

264850

2

Long-Sleeve Jersey Dress

Petite

39.95

930405

4

Solid Crewneck Tee

Medium

12.95

293004

1

Cotton Comfort Open Bottom Pant XLarge

17.85

924515

1

Hooded Full-Zip Sweatshirt

S

69.95

405945

3

Plaid Pinpoint Dress Shirt

22 35-36 35.85

294936

2

Cool-Dry Soft Cup Bra

36D

15.55

294545

2

Ladies Hooded Sweatshirt

Medium

45.75

820465

2

Cotton Knit Blazer

M

295.95

294694

2

Denim Blazer - Natural Brown

Large

75.85

924094

3

Texture-Striped Pleated Dress Pants

44x30

32.85

359405

3

Iron-Free Pleated Khaki Pants

32x32

39.95

192004

3

Sunglasses

15.85

Imagine you want to create a mechanism of calculating the price of an item after a discount has been applied to it. Such 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:

If you are planning to create a procedure that takes an argument and know that the argument will likely have the same value most of the time, you can provide that value as parameter but leave a room for other values of that argument. A value given to an argument is referred to as default. What this implies is that, when the user calls that stored procedure, if the user doesn't provide a value for the argument, the default value would be used. To create a procedure that takes an argument that carries a default value, after declaring the value, on its right 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 procedure that takes a default argument, you don't have to provide a value for the argument if the default value suits you. Based on this, the above procedure can be called as follows:

If the default value doesn't apply to your current calculation, you can provide a value for the argument. Here is an example:

Using this same approach, you can create a procedure that takes more than one argument with default values. To provide a default value for each argument, after declaring it, type the desired value to its right side. Here is an example of a 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:

When calling a procedure that takes more than one argument and all arguments having default values, you don't need to provide a value for each argument, you can provide a value for only one or some of the arguments. The above 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 procedure that takes more than one argument, you didn't have to provide the values of the argument in the exact order they appeared in the procedure, you just had to type the name of each argument and assign it the desired value. In the same way, if a procedure takes more than one argument and some of the arguments have default values, when calling it, you can provide the values in the order of your choice, by typing the name of each argument and assigning it the desired value. Based on this, the above procedure can be called with 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

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

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,

6. Delete the contents of the query window

Output Parameters Many languages use the notion of passing an argument by reference. This type of argument is passed to a procedure but it is meant to return a value. Transact-SQL uses the same technique. In other words, you can create a procedure that takes a parameter but the purpose of 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 procedure, after the name of the procedure, if you want the procedure to take arguments, type them. Otherwise, omit them. On the other hand, you must pass at least one argument,

name it starting with the @ symbol, specify its data type, and enter the OUTPUT keyword on its right. 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 must follow is that, before the end of the procedure, you must have specified a value for the OUTPUT argument. That's the value that the procedure will return. 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 procedure, you must pass an argument for the OUTPUT parameter and, once again, you must type OUTPUT to the right side of the argument. Remember that the procedure would return the argument. This means that, after calling the procedure, you can get back the OUTPUT argument and use it as you see fit. Here is an 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 and records of its database. This means that you can access the columns and records as long as you specify the table or the view, which is done with a FROM clause associated with a SELECT statement. Consider the following stored procedure created in a database that contains a table named Students: USE ROSH; GO CREATE PROCEDURE ShowStudentsFullNames @FullName varchar(42) OUTPUT AS SELECT @FullName = LastName + ', ' + FirstName FROM Students; GO When you execute this procedure, it would work on the records of the table. One of the particularities of a procedure that takes an OUTPUT argument is that it can return only one value. Consider the following example of executing the above procedure:

When calling such a procedure, if you don't specify a condition to produce one particular result, the SQL interpreter in this case would select the last record. This means that you should always make sure that your procedure that takes an OUTPUT parameter would have a way to isolate a result. If the procedure processes a SELECT 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 When this procedure is executed, it would produce only the record stored in the 8th position of the table.

Lesson Summary Exercises 1. Create a stored procedure named ProcessPayroll that takes 11 arguments: a.The number of hours worked for the first week (passed by value) b.The number of hours worked for the second week (passed by value) c.A number that represents the number of regular hours worked for the two weeks (passed by reference)

d.A number for the salary paid for the regular hours of the two weeks (passed by reference)

Related Documents

Introduction Sql Server
November 2019 22
Sql Server
November 2019 28
Sql Server
November 2019 18
Sql Server
May 2020 11
Sql Server
November 2019 35