Home

Data Entry and Update Using Stored Procedures

 
 

Data Entry Using a Stored Procedure

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:

IF EXISTS (SELECT name 
	   FROM   sysobjects 
	   WHERE  name = N'CreateNewRecord' 
	   AND 	  type = 'P')
    DROP PROCEDURE CreateNewRecord
GO

CREATE PROCEDURE CreateNewRecord 
  @FirstName VarChar(20),
  @LastName VarChar(20),
  @Gender int,
  @Notes Text
AS
  INSERT Persons(FirstName, LastName, GenderID, Notes)
              VALUES(@FirstName, @LastName, @Gender, @Notes)
GO

After creating the stored procedure, you can then create an application design the form to include the fields for columns represented in the table.

Practical Learning: Performing Data Entry Using a  Stored Procedure

 

 
  1. In Server Explorer, expand the ISC1 database. Right-click its Store Procedure node and click New Stored Procedure
  2. Complete it as follows:
     
  3. Save and close the procedure window
  4. Open the CIS2 project and display the OrderProcessing form (OrderProcessing.cs [Design])
  5. Add a new button to the form
  6. Change its Name to btnNewOrder and its Text to New Order
     
  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
    		
    
    
    		private void btnNewRecord_Click(object sender, System.EventArgs e)
    		{
    			// Find out the state (actually caption) of the New Order button
    			if( this.btnNewOrder.Text.Equals("New Order") )
    			{
    				// If it is displaying New Order, then reset the form to get ready
    				// for a new customer order
    				this.txtOrderID.Text = "";
    				this.cboProcessedBy.SelectedIndex = 0;
    				this.dtpOrderDate.Value = DateTime.Today;
    				this.dtpOrderTime.Value = DateTime.Now;
    				this.cboFlavor.SelectedIndex = 0;
    				this.cboContainer.SelectedIndex = 0;
    				this.cboIngredient.SelectedIndex = 0;
    				this.txtScoops.Text = "1";
    				// Set the caption of the button to Submit
    				// to indicate that the button will need to be clicked 
    				// to validate an order
    				this.btnNewOrder.Text = "Submit";
    			}
    			else // If the button is displaying Submit, then process an order
    			{
    				// 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("ProcessNewOrder", this.sqlConnection1);
    				SqlDataAdapter sdaNew = new SqlDataAdapter(cmdNew);
    
    				// Let the SQL command know the type of command we are going to use
    				// In this case, it is a stored procedure
    				cmdNew.CommandType = CommandType.StoredProcedure;
    
    				// We will need a SQL parameter to carry the arguments
    				// Declare its variable
    				SqlParameter parNew   = new SqlParameter();
    				// Specify the name of the argument
    				parNew.ParameterName  = "@ProcessedBy";
    				// Specify the SQL data type of the argument
    				parNew.SqlDbType      = SqlDbType.Int;
    				// Specify the value passed as argument
    				parNew.Value          = this.cboProcessedBy.SelectedIndex;
    
    				// Once the argument is ready, add it to the list of arguments
    				cmdNew.Parameters.Add(parNew);
    
    				parNew   = new SqlParameter();
    				parNew.ParameterName  = "@DateOrdered";
    				parNew.SqlDbType      = SqlDbType.SmallDateTime;
    				parNew.Value          = this.dtpOrderDate.Value;
    				cmdNew.Parameters.Add(parNew);
    
    				parNew   = new SqlParameter();
    				parNew.ParameterName  = "@TimeOrdered";
    				parNew.SqlDbType      = SqlDbType.SmallDateTime;
    				parNew.Value          = this.dtpOrderTime.Value;
    				cmdNew.Parameters.Add(parNew);
    
    				parNew   = new SqlParameter();
    				parNew.ParameterName  = "@ContainerType";
    				parNew.SqlDbType      = SqlDbType.Int;
    				parNew.Value          = this.cboContainer.SelectedIndex;
    				cmdNew.Parameters.Add(parNew);
    			 
    				parNew   = new SqlParameter();
    				parNew.ParameterName  = "@SelectedFlavor";
    				parNew.SqlDbType      = SqlDbType.Int;
    				parNew.Value          = this.cboFlavor.SelectedIndex;
    				cmdNew.Parameters.Add(parNew);
    			 
    				parNew   = new SqlParameter();
    				parNew.ParameterName  = "@NbrOfScoops";
    				parNew.SqlDbType      = SqlDbType.Int;
    				parNew.Value          = int.Parse(this.txtScoops.Text);
    				cmdNew.Parameters.Add(parNew);
    			 
    				parNew   = new SqlParameter();
    				parNew.ParameterName  = "@WhatIngredient";
    				parNew.SqlDbType      = SqlDbType.Int;
    				parNew.Value          = this.cboIngredient.SelectedIndex;
    				cmdNew.Parameters.Add(parNew);
    			
    				// Inform the user about the action that is going to occur
    				// (You can also do this after the action has been carried
    				MessageBox.Show("A new customer order has been created");
    
    				// Update the data set with the new information from the data adapter
    				sdaNew.Fill(this.dsOrders1, "Orders");
    
    				// Change the caption of the button to inform the user
    				this.btnNewOrder.Text = "New Order";
    
    				// And move to the last record
    				this.BindingContext[this.dsOrders1, "Orders"].Position = 
    					this.BindingContext[this.dsOrders1, "Orders"].Count - 1;
    			}
    		}
    	}
    }
  8. Execute the application
     
  9. Close the form and return to your programming environment

General Data Update Using a Stored Procedure

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.

Criterion-Based Data Update Using a Stored Procedure

One of the jobs of a database developer or administrator is to update records when there is a new request. For example, imagine a company has decided to change the minimum salary of all employees and the manager asks you to make this change. If the company is small as having less than 10 employees, you can easily open the table or the form that holds the employees records, manually examine the employees with the lowest salary, and then change those who have a salary below the company's new set. You can also create an update query that would perform the task. The job here is to check all salaries but to make a change only to those that respond to a specific criterion. For example, if you must change the minimum salary to 8.55, your change would affect only those employees who are making less than $8.55/hr. This type of assignment can be handled by a stored procedure by including an UPDATE statement as part of the procedure. 

Practical Learning: Updating Data Using a Stored Procedure

  1. In Server Explorer, right-click the Stored Procedure node of the SuperMarket database and click New Stored Procedure
  2. Change the statement as follows:
     
  3. Save and close the procedure window
  4. Open the SuperMarket1 project
  5. Display the form (Form1.cs [Design]) and change its design as follows:
     
    Control Name Caption/Text Other Properties
    Label   Set the company's new minimum salary to $ Anchor: Bottom, Left
    TextBox txtNewMinSal 6.55 TextAlign: Right
    Anchor: Bottom, Left
    Button btnNewMinSal Submit Anchor: Bottom, Left
  6. Double-click the new Submit button and implement its Click event as follows:
     
    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();
    
    	// We will need a SQL parameter to carry the argument
    	// Declare its variable
    	SqlParameter parNew   = new SqlParameter();
    	// Specify the name of the argument
    	parNew.ParameterName  = "@NewSalary";
    	// Specify the SQL data type of the argument
    	parNew.SqlDbType      = SqlDbType.SmallMoney;
    	// Specify the value passed as argument
    	parNew.Value          = this.txtNewMinSal.Text;
                
    	// Once the argument is ready, add it to the list of arguments
    	cmdNew.Parameters.Add(parNew);
    	// Let the SQL command know the type of command we are going to use
    	// In this case, it is a stored procedure
    	cmdNew.CommandType = CommandType.StoredProcedure;
    			
    	// Inform the user about the action that is going to occur
    	// (You can also do this after the action has been carried
    	MessageBox.Show("The new minimum salary throughout the company has been set to $" +
                                this.txtNewMinSal.Text);
    
    	// 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
 
 

Previous Copyright © 2004-2006 FunctionX, Inc.