Practical Learning: Creating The Database
Practical Learning: Creating The Database
When programming in SQL, you have probably created various types of SQL
statements to execute many common actions. You use SQL statements to create
databases, create tables, modify tables, or perform data entry. These actions are
performed by you the programmer as you need them. In SQL, you can create a
statement to be treated as an object and use it only when needed. You can create
the statement as an object called a stored procedure.
1.
Practical Learning: Creating the Database
Start Microsoft SQL Server Management Studio and click Connect to connect
to the database server
2. To create a database, right-click the Databases node and click New
Database...
3. Set the Database Name to SuperMarket and click OK
4. Expand the SuperMarket node and the Tables node
5. Right-click Tables and click click New Table...
6. Set the name of the first column to EmployeeID and its data Type to int
7. In the lower section of the window, expand the Identity Specification and set
the (Is Identity) to Yes
8. Right-click EmployeeID and click Set Primary Key
9. Create the other columns as follows:
Column
Data Type Allow Nulls
Name
EmployeeID
FirstName varchar(20)
LastName varchar(20) Unchecked
FullName varchar(50)
1. Under the SuperMarket database, expand the Programmability node and the Stored
Procedures node
2. Right-click Stored Procedures and click New Stored Procedure...
3. Complete the file as follows:
4.
--
======================================================
-- Author: Mon'a Zo'o
-- Create date: 10 October 2006
-- Description: Specifies the full name of each employee
--
======================================================
CREATE PROCEDURE CreateFullNames
AS
BEGIN
UPDATE Employees
SET FullName = LastName + ', ' + FirstName
FROM Employees
END
GO
--
======================================================
On the Standard toolbar, click the Execute button
5. Right-click Stored Procedures and click Refresh. Notice that it has a new node named
dbo.CreateFullNames
There are certainly various ways you can use a SQL stored procedure in a Windows
application but the classic way consists of using a command object. The .NET
Framework's SqlCommand class has a constructor that takes two arguments, the
first of which is a string that represents the name of the stored procedure. When
passing the string to the command object, you must indicate that it (the string)
represents the name of a stored procedure. To support this, the command object
has a property named CommandType, which is an enumeration and one of its
elements is called StoredProcedure. After creating the command object, pass it to
a data adapter, fill the table of the data set with the data from the data adapter, then
fill the table adapter.
8. Click OK
9. In the Data Source Configuration Wizard, make sure the SuperMarket
connection is selected and click Next
10. Change the name of the connection string to cstSuperMarket and click
Next
11.Expand Tables and Stored Procedures
12.Click the check boxes of Employees and CreateFullNames
13. Change the name of the DataSet to dsSuperMarket
14.Click Finish
15.In the Data Sources window, click Employees and click the arrow of its
combo box to select DataGridView (it should be selected already as the
default).
Drag the Employees node and drop it on the form
16.While the DataGridView control is still selected on the form, in the
Properties window, click the ellipsis of the Columns field and make the
following changes:
Selected
HeaderText Width
Columns
EmployeeID Employee ID 75
FirstName First Name 80
LastName Last Name 80
EmailAddress Email Address 130
sdaSuperMarket.Fill(dsSuperMarket.Employees);
employeesTableAdapter.Fill(dsSuperMarket.Employees);
24.
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
Execute the application to see the result
25.Click the Create Full Names button:
Fundamentals of Stored Procedures
Introduction
Imagine that your create a database that includes employees. When you want to pe
employees, you would need their weekly hours and their hourly salaries. To calcu
salary, you would write an equation such as:
Introduction
To create a new procedure in SQL Query Analyzer, after selecting the database
(either from the combo box on the toolbar or with the USE keyword), you can
type code based on the syntaxes we will learn shortly.
Like everything in your database, you must name your procedure. The name of
a procedure can be any string that follows the rules we reviewed for naming
objects. There are some other rules or suggestions you should or must follow
when naming your procedure. For example, refrain from starting the name of a
procedure with sp_ because it would conflict with some of the procedures that
already ship with SQL Server.
The section, group of words, or group of lines after the AS keyword is called the
body of the procedure. It states what you want the procedure to do or what you
want it to produce.
EXECUTE ListOfMakes
You can also create a procedure that selects more than one column from a
table. As done with the SELECT keyword in data analysis, you would separate
each item of the list with a comma, except for the last. Here is an example:
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:
After creating a procedure, to get its result, you would need to execute it (in
other programming languages, we would say that, in order to use a function,
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
After a procedure has been executed, it is saved using its name. Since it
becomes stored as an integral part of the database, a SQL procedure is also
called a Stored Procedure.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace SuperMarket1
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
. . . No Change
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
// Let the user know that the assignment has been carried
MessageBox.Show("An email address has been created for
employees");
}
}
}
4. Test the application:
5. Close the form and return to your programming environment
Deleting a Procedure
Introduction
Imagine you are creating an application for a department store that sometimes
applies discounts of 10%, 20%, 40%, 55%, 70%, etc on items its 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.
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. We
will learn how this is done.
Passing Arguments
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 parameter 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
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.
Alternatively, you can provide the value for each parameter in the order of your
choice. In this case, you must type the name of each parameter and assign it the
corresponding value.
// Update the data set with the new information from the data adapter
sdaNew.Fill(dsEmployees, "Employees");
// Update the information displayed in the datagrid
this.sqlDataAdapter1.Fill(this.dsEmployees1, "Employees");
}
7. Execute the application
8. Close the form and return to your programming environment
Default Arguments
Imagine you create a table for a department store and the table would be used
to hold the names and prices of items (in this example, the table is called
SaleItems):
Suppose you have filled the table with a few items 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:
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:
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:
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
appear in the procedure, you just had to type the name of each argument and
assign it the corresponding 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:
Output Parameter
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, type the
OUTPUT keyword on the right side of the parameter. A syntax you can use is:
Probably the best attribute of a stored procedure is that it allows the developer
to have a direct programmatic with to the back-end database. Based on this
relationship, you can use a stored procedure to perform data entry.
To create a new record in a table, you can use the INSERT TABLE expression
of the SQL. If the table doesn't have a primary key, you can create an
argument for each column of the table. If the table has a primary key, you can
create an argument for each column of the table but you should/must omit one
for the primary key. Here is an example of such a procedure from a database
called Familia that has a table named Persons with the PersonID(Primary Key),
FirstName, LastName, GenderID, and Notes columns:
7. Double-click the New Order button and implement its Click event
as follows:
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace CIS2
{
/// <summary>
/// Summary description for OrderProcessing.
/// </summary>
public class OrderProcessing : System.Windows.Forms.Form
{
. . . No Change
// Update the data set with the new information from the data
sdaNew.Fill(this.dsOrders1, "Orders");
When a user is navigating through records and find information that is not
accurate, if the user makes a change, you must provide a mechanism to keep
the updated value as we did in the previous lesson. This scenario that involves
changing existing data of records can be handled by a stored procedure. This is
usually done by including an UPDATE statement as part of the procedure.
3. Save
close the procedure window
4. Open the SuperMarket1 project
5. Display the form (Form1.cs [Design]) and change its design as follows:
Other
Control Name Caption/Text
Propertie
Anchor:
Label Set the company's new minimum salary to $ Bottom,
Left
TextAlign
Right
TextBox txtNewMinSal 6.55 Anchor:
Bottom,
Left
Anchor:
Button btnNewMinSal Submit Bottom,
Left
6.
Double-click the new Submit button and implement its Click event as follows:
7.
private void btnNewMinSal_Click(object sender, System.EventArgs e)
{
// Create a new SqlCommand command, passing it the name of
// the stored procedure we want to call and attaching it to
// the existing SQL connection
SqlCommand cmdNew = new SqlCommand("SetNewMinSalary",
this.sqlConnection1);
SqlDataAdapter sdaNew = new SqlDataAdapter(cmdNew);
DataSet dsEmployees = new DataSet();
// Update the data set with the new information from the data adapte
sdaNew.Fill(dsEmployees, "Employees");
// Update the information displayed in the datagrid
this.sqlDataAdapter1.Fill(this.dsEmployees1, "Employees");
}
Execute the application