Showing posts with label asp net page. Show all posts
Showing posts with label asp net page. Show all posts

Sunday, November 25, 2007

Using Output Parameters with a Stored Procedure

One of the ways that you can use a stored procedure is to have it return data through output parameters. Then after the call to the stored procedure you can display the values returned to you. For example, you might use a stored procedure to return summary information about a table. This could be done through output parameters. The technique presented in this section of the chapter shows you how to use output parameters.


USE IT A Command object contains a collection of Parameter objects. These parameters are values that the stored procedure passes back to you after the call is complete. This ASP.NET page calls a stored procedure that returns values. The values returned are the total number of records in the Employees table and the name of the employee who is paid the most.

The stored procedure has this definition:

CREATE PROCEDURE Tablelnfo
@RecordCount integer OUTPUT,
@TopSalaryName varchar(100) OUTPUT
AS
Select @RecordCount = Count(EmpID) From Employees Select @TopSalaryName = LastName + ' + FirstName
From Employees Where Salary = (Select Max(Salary) From Employees)
Totice that the two parameters are declared as output parameters. In the first query, one of the put parameters is set to the record count. In the second query the other parameter is set to the name he employee who is paid the most.

That stored procedure is called when the ASP.NET page loads:

Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
[n that procedure you will need a Connection object:
Dim DBConn as SQLConnection that points to the SQL Server database:
DBConn = New SQLConnection("server=localhost;" _
& "Initial Catalog=TT;"
& "User Id=sa;"
& "Password=yourpassword;")
You will need a Command object: Dim DBSP As New SQLCommand

You also will need two Parameter objects. The first has its name match the first parameter in the stored procedure and is of the same data type:

Dim parRecordCount as New _ SqlParameter("@RecordCount", SqlDbT e.Int)

The second parameter is set to the name and type of the second output parameter in the stored procedure:

Dim parTopSalaryName as New _ SqlParameter("@TopSalaryName", SqlDbType.VarChar, 100)

Both parameters are set to output parameters using the Direction property:

parRecordCount.Direction = ParameterDirection.Output parTopSalaryName.Direction = ParameterDirection.Output

Next, those parameters are added to the Parameters collection of the Command object:

DBSP.Parameters.Add(parRecordCount) DBSP.Parameters.Add(parTopSalaryName)

The CommandText property of the Command object is set to the name of the stored procedure: DBSP.CommandText = "TableInfo" and the command type is set to stored procedure: DBSP.CommandType = CommandType.StoredProcedure

The Command object will connect to the database through the Connection object:

DBSP.Connection = DBConn DBSP.Connection.Open
The stored procedure can then be executed: DBSP.ExecuteNonQuery()

After the call to the stored procedure you can use the values in the output parameters through the Value property:

lblMessage.Text = "Total Employees: "
& parRecordCount.Value _
& "

Highest Paid: "
& parTopSalaryName.Value
Visitors would then see through the Label control the total number of employees and the highest salary amount.

Sending Data to a Stored Procedure Through Input Parameters

If you are working towards making your ASP.NET application more efficient and that application connects to an SQL Server database, you will want to create stored procedures that do basic things like adding records, deleting records, and other such tasks. With these types of stored procedures, you need to pass data into them. This technique shows you how to call a stored procedure that needs to have parameters passed into it.


USE IT The ASP.NET page created for this technique allows visitors to add a record to the Employees table. Instead of using an Insert statement in the ASP.NET code, a stored procedure is called to add the record.

That stored procedure has this definition:

CREATE PROCE @LastName va
DURE AddEmployee rchar(50),
@FirstName varchar(50), @BirthDate datetime, @Salary money,
@EmailAddress varchar(50) AS
Insert Into Employees (LastName, FirstName, BirthDate,
Salary, EmailAddress) values
@LastName, @FirstName, @BirthDate,
@Salary, @EmailAddress) GO
Notice that the stored procedure has five input parameters. Those parameters are used in the Insert statement in the stored procedure.

On the ASP.NET page, visitors enter the values for the new employee record into TextBox control. When they click the Button control, this procedure fires, adding the new record by calling the stored procedure:

Sub SubmitBtn_Click(Sender As Object, E As EventArgs)
Within the procedure, you need these data objects:
Dim DBConn as SQLConnection Dim DBAdd As New SQLCommand
You need to start by connecting to the SQL Server database:
DBConn = New SQLConnection("server=localhost;"
& "Initial Catalog=TT;" _
& "User Id=sa;" _
& "Password=yourpassword;")
Next, you place the SQL syntax into the Command object that calls the stored procedure:

DBAdd.CommandText = "Exec AddEmployee " _
& "'" & Replace(txtLastName.Text, "'", """) _
&
& ''" & Replace(txtFirstName.Text, "'", """)
&
& "'" & Replace(txtBirthDate.Text, "'", """)
& HI,
& Replace(txtSalary.Text, "'", """) & ", "
& "'" & Replace(txtEmailAddress.Text, "'", """)
Notice that the call passes in five parameters, the values for the new record. A comma separate each parameter.

The Command object will connect to the database through the Connection object:

kdd.Connection = DBConn kdd.Connection.Open

and the stored procedure can be executed:

kdd.ExecuteNonQuery()

Saturday, November 24, 2007

Working with Transactions with an SQL Server Database

Transactions provide a way for you to group together database executions as a group so that they succeed or fail together. For example, if you had an e-commerce site you may have code that allows visitors to add a quantity of an item to their shopping cart. When you do that you also want to remove the number of items ordered from your inventory.


Therefore, you have two actions that you need to execute. You want to add items to a shopping cart and you want to remove items from inventory.

These executions need to happen as a group. You don't want to add items to the shopping cart if something goes wrong with removing them from inventory. And the opposite is also true.

Therefore, the database executions need to be grouped in a Transaction. This technique shows you

how to use a Transaction object with an SQL Server database.

This ASP.NET page contains SQL Delete statements that delete records from the Employees table. But the records are not deleted because they are in a transaction and the transaction is not committed to the database.

The code that performs this task fires when the ASP.NET page loads:

Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs) Within that procedure you will need a Connection object and a Command object:

Dim DBConn as SQLConnection Dim DBDelete As New SQLCommand

You will also need a Transaction object:

Dim DBTrans As SQLTransaction

You start by connecting to the SQL Server database:

DBConn = New SQLConnection("server=localhost;"
& "Initial Catalog=TT;" _
& "User Id=sa;" _
& "Password=yourpassword;")
and opening that connection:
DBConn.Open()

You then start a transaction by calling the BeginTransaction method of the Connection object. That method returns an open transaction, which is placed into the local Transaction object:

DBTrans = DBConn.BeginTransaction()

The Command object will connect to the database through the Connection object:

DBDelete.Connection = DBConn

It will also use the Transaction object:

DBDelete.Transaction = DBTrans

Next, two records are deleted and executed from the Employees table:

DBDelete.CommandText = "Delete From Employees
& "Where EmpID = 1" DBDelete.ExecuteNonQuery() DBDelete.CommandText = "Delete From Employees
& "Where EmpID = 2"DBDelete.ExecuteNonQuery()

But the records are not actually deleted from the database since the RollBack method of the Transaction object is called:

DBTrans.RollBack()
lblMessage.Text = "No action was taken."

The RollBack method causes the queries that were executed within the Transaction object to be cancelled.

You could instead call the Commit method:

'DBTrans.Commit()

['his method causes the pending execute statements to be executed as a group so that they fail or succeed together.

Internet Blogosphere