SQL Operations: The Microsoft SQL Server Management Studio
SQL Operations: The Microsoft SQL Server Management Studio
<a
SQL Operations
The Microsoft SQL Server Management Studio
Introduction
There are many tools you will use in Microsoft SQL server. One of them is called Microsoft SQL Server Management Studio. To access it, you can click Start -> (All) Programs -> Microsoft SQL Server 2005 -> SQL Server Management Studio. A dialog box would come up but you can click Cancel on it:
The top section of the SQL Server Management Studio displays the classic title bar of a regular window, with an icon on the left, followed by the title of the application, and the system buttons on the right side. Under the title bar, the menu bar displays categories of menus that you will use to perform the various necessary operations. A toolbar displays under the main menu. The left side of the interface displays the Object Explorer window, with its title bar labeled Object Explorer. On the right side of the Object Explorer title, there are three buttons. If you click the first button that points down, a menu would appear, which allows you to specify whether you want the window to be floated, docked, or tabbed. This window is dockable, meaning you can move it from the left side to another side on the interface. To do this, you can click and drag its title bar to a location of your choice. The window is also floatable, which means you can place it somewhere in the middle of the interface:
To place the window back to its previous position, you can double-click its title bar. The window can also be tabbed. This means that the window can be positioned either vertically or horizontally. The right side of the window is equipped by a window whose tab is labeled Summary. This area will be used to display either the contents of what is selected in the Object Explorer, or to show a result of some operation. As you will see later on, many other windows will occupy the right section but they will share the same area. To make each known it will be represented with a tab and the tab shows the name (or caption) of a window.
The name of the server is followed by parentheses. In the previous section, we saw that, to establish a connection to a server, you must authenticate yourself. In some cases you may use the same account over and over again. In some other cases you may have different accounts that you use for different scenarios, such as one account for database development, one account for database management, and/or one account for database testing. Some operations cannot be performed by some accounts. When performing some operations, you should always know what account you are using. You can check this in the parentheses of the server name. In the following connection, an account called Administrator is currently connecting to a server named Central:
When the server name is selected in the Object Explorer, the whole caption of its node displays in the Summary window. Probably the most regular node you will be interested in, is labeled Databases. This node holds the names of databases on the server you are connecting. Also, from that node, you can perform almost any necessary operation of a database. To see most of the regularly available actions, you can
expand the Databases node and some of its children. You can then right-click either Databases or one of its child nodes.
Introduction to Code
Although you will perform many of your database operations visually, some other operations will require that you write code. To assist with with this, Microsoft SQL Server provides a code editor and various code templates. To open the editor, on the Standard toolbar, you can:
q
Press Ctrl + N On the main menu, you can click File -> New -> Query With Current Connection On the Standard toolbar, click the New Query button In the Object Explorer, right-click the name of the server and click New Query
This would create a new window and position it on the right side of the interface. Whether you have already written code or not, you can save the document of the code editor at any time. To save it:
q
You can press Ctrl + S On the main menu, you can click File -> Save SQLQueryX.sql... On the Standard toolbar, you can click the Save button
You will be required to provide a name for the file. After saving the file, its name would appear on the tab of the document.
tradition to write SQL's own words in uppercase. This helps to distinguish SQL instructions with the words you use for your database. As we will learn in this and the other remaining lessons of this site, you use SQL by writing statements. To help you with this, Microsoft SQL Server provides a window, also referred to as the Query Window, that you can use to write your SQL code. To access it, on the left side of the window, you can right-click the name of the server and click New Query. In the same way, you can open as many instances as the New Query as you want. When the Query window comes up, it display a blank child window in which you can write your code. The code you write is a document and it can be saved as a file. The file would have the extension . sql. Every time you open a new query, it is represented with a tab. To switch from one code part to another, you can click its tab. To dismiss an instance of the query, first access it (by clicking its tab), . If you had written code in the query window, when then, on the right side, click the close button you close it, you would be asked to save your code. If you want to preserve your code, then save it. If you had already executed the code in the window (we will learn how to write and execute SQL code), you don't have to save the contents of the window.
Executing a Statement
In the next sections and lessons, we will learn various techniques of creating SQL statements with code. By default, when a new query window appears, it is made of a wide white area where you write your statements:
After writing a statement, you can execute it, either to make it active or simply to test it. To execute a statement:
q
You can press F5 On the main menu, you can click Query -> Execute On the SQL Editor toolbar, you can click the Execute button You can right-click somewhere in the code editor and click Execute
When you execute code, code editor becomes divided into two horizontal sections:
Also, when you execute code, the interpreter would first analyze it. If there is an error, it would display one or more red lines of text in its bottom section. Here is an example:
If there is no error in the code, what happens when you execute a statement depends on the code and the type of statement.
/* First find out if the database we want to create exists already */ A comment can also be spread on more than one line, like a paragraph. Here is an example: /* First find out if the MotorVehicleDivision database we want to create exists already. If that database exists, we don't want it anymore. So, delete it from the system. */ Transact-SQL also supports the double-dash comment. This comment applies to only one line of text. To use it, start the line with --. Anything on the right side of -- is part of a comment and would not be considered as code. Here is an example: -- ============================================= -- Database: MotorVehicleDivision -- ============================================= /* First find out if the MotorVehicleDivision database we want to create exists already. If that database exists, we don't want it anymore. So, delete it from the system. */
Time to GO
To separate statements, that is, to indicate when a statement ends, you can use the GO keyword (in reality and based on SQL standards, it is the semi-colon that would be required, but the Microsoft SQL Server interpreter accepts GO as the end of a statement).
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 The item to display can be anything that is allowed and it is provided on the right side of PRINT. If it is a regular constant number, simply type it on the right side of PRINT. Here is an example:
The item to display can also be an operation or the result of an operation. If you want to display a character, a word, or a sentence, include it between single-quotes. If you want to include a singlequote in your statement, double it; that is, write it twice. Here is an example:
You can also display an expression as a combination of number(s) and sentences as we will learn later.
SELECT
SELECT Anything
The SELECT operator can be used, among other things, to display a value. The SELECT keyword uses the following syntax: SELECT What
file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson03.htm (8 of 17)11/27/2008 8:03:58 AM
Based on this, to use it, where it is needed, type SELECT followed by a number, a word, a string, or an expression. The item to display follows some of the same rules as PRINT. One of the differences between PRINT and SELECT is that:
q
PRINT is mostly used for testing a simple value, a string, or an expression. Therefore, it displays its results in a regular white window under a tab labeled Messages. PRINT can be used with only one value SELECT is the most regularly used SQL operator. We will see that it is used to retrieve records from a table. For this reason, SELECT displays its results in an organized window made of categories called columns, under a tab labeled Results. SELECT can be used with more than one value
As done for PRINT, to display a sentence using SELECT, type it in single-quotes on the right side of this operator. Here is an executed example:
As mentioned already, unlike PRINT, SELECT can be used to display more than one value. The values must be separated by commas. Here is an example: SELECT 'Hourly Salary', 24.85 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'; If the item on the right side of AS is in different words, you should include it in single-quotes or put them in inside of an opening square bracket "[" and a closing square bracket "]". Here is an example: 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; This would produce:
The above statement could also be written as follows: SELECT 'James Knight' As [Full Name], 20.48 AS [Hourly 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 -6 -5 -5 -4 -4 -3 -3 -2 -2 -1 0 -1 1 2 3 4 5 6 + 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 1 2 3 4 5 6 +
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
file:///C|/Documents%20and%20Settings/michael.musyoki/Desktop/SS/Lesson03.htm (13 of 17)11/27/2008 8:03:58 AM
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.
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 1 0
~Bit 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 ~Value
1 0
1 0
1 0
1 0
1 0
0 1
0 1
0 1
Bit1 0 1 0 1
Bit2 0 0 1 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). Lets 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
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
Bit1 0 1 0 1
Bit2 0 0 1 1
Bit1 | Bit2 0 1 1 1
Once again, lets 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
You can also let the compiler perform the operation and produce a result. Here is an example: PRINT 187 | 242 This would produce 251
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
If the interpreter performs this operation, it can produce a result as in the following example: PRINT 187 ^ 242; This would produce 73.
Lesson Summary
Exercise: Utility Company
1. Open a query window from the UtilityCompany1 database 2. Create and execute an operation that can multiply 224 kWh by $0.0900/kWh 3. Create and execute an operation that can add $8.50 to the result of multiplying 148 kWh by 0.0650/kWh
Exercise: US States
1. Do some research and find out what are the states that belong to the New England region 2. On a piece of paper, write the name of each state that is part of New England, followed by its population (the population of that state) 3. Connect to the server from the Command Prompt and access the UnitedStatesRegions1 database 4. Write and execute an expression that calculates the total population of New England 5. Exit the Command Prompt
Next