You are on page 1of 11

Executing a Command

Each .NET Framework data provider included with the .NET Framework has its own command object that inherits from DbCommand. The .NET Framework Data Provider for OLE DB includes an OleDbCommand object, the .NET Framework Data Provider for SQL Server includes a SqlCommand object, the .NET Framework Data Provider for ODBC includes an OdbcCommand object, and the .NET Framework Data Provider for Oracle includes an OracleCommand object. Each of these objects exposes methods for executing commands based on the type of command and desired return value, as described in the following table.
command ExecuteReader ExecuteScalar ExecuteNonQuery ExecuteXMLReader Return Value Returns a DataReader object. Returns a single scalar value. Executes a command that does not return any rows. Returns an XmlReader. Available for a SqlCommand object only.

Each strongly typed command object also supports a CommandType enumeration that specifies how a command string is interpreted, as described in the following table.
CommandType Description Text An SQL command defining the statements to be executed at the data source. StoredProcedur The name of the stored procedure. You can use the Parameters property of a command to e access input and output parameters and return values, regardless of which Execute method is called. When using ExecuteReader, return values and output parameters will not be accessible until the DataReader is closed. TableDirect The name of a table.

Executing a Command
static void GetSalesByCategory(string connectionString, string categoryName) { using (SqlConnection connection = new SqlConnection(connectionString)) { // Create the command and set its properties. SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "SalesByCategory"; command.CommandType = CommandType.StoredProcedure; // Add the input parameter and set its properties. SqlParameter parameter = new SqlParameter(); parameter.ParameterName = "@CategoryName"; parameter.SqlDbType = SqlDbType.NVarChar; parameter.Direction = ParameterDirection.Input; parameter.Value = categoryName; // Add the parameter to the Parameters collection. command.Parameters.Add(parameter);

Code - I

Executing a Command
// Open the connection and execute the reader. connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Console.WriteLine("{0}: {1:C}", reader[0], reader[1]); } } else { Console.WriteLine("No rows found."); } reader.Close(); } }

Code - I

Obtaining a Single Value from a Database


You may need to return database information that is simply a single value rather than in the form of a table or data stream. For example, you may want to return the result of an aggregate function such as COUNT(*), SUM(Price), or AVG(Quantity). The Command object provides the capability to return single values using the ExecuteScalar method. TheExecuteScalar method returns, as a scalar value, the value of the first column of the first row of the result set.

Obtaining a Single Value from a Database


static public int AddProductCategory(string newName, string connString) { Int32 newProdID = 0; string sql = "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); " + "SELECT CAST(scope_identity() AS int)"; using (SqlConnection conn = new SqlConnection(connString)) { SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.Add("@Name", SqlDbType.VarChar); cmd.Parameters["@name"].Value = newName; try { conn.Open(); newProdID = (Int32) cmd.ExecuteScalar(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } return (int)newProdID; }

Code

Modifying Data with Stored Procedures


Stored procedures can accept data as input parameters and can return data as output parameters, result sets, or return values. The sample below illustrates how ADO.NET sends and receives input parameters, output parameters, and return values. The example inserts a new record into a table where the primary key column is an identity column in a SQL Server database. NoteIf you are using SQL Server stored procedures to edit or delete data using a SqlDataAdapter, make sure that you do not use SET NOCOUNT ON in the stored procedure definition. This causes the rows affected count returned to be zero, which the DataAdapter interprets as a concurrency conflict. In this event, a DBConcurrencyException will be thrown.

Modifying Data with Stored Procedures


The sample uses the following stored procedure to insert a new category into the Northwind Categories table. The stored procedure takes the value in the CategoryNamecolumn as an input parameter and uses the SCOPE_IDENTITY() function to retrieve the new value of the identity field, CategoryID, and return it in an output parameter. The RETURN statement uses the @@ROWCOUNT function to return the number of rows inserted. other CREATE PROCEDURE dbo.InsertCategory @CategoryName nvarchar(15), @Identity int OUT AS INSERT INTO Categories (CategoryName) VALUES(@CategoryName) SET @Identity = SCOPE_IDENTITY() RETURN @@ROWCOUNT The following code example uses the InsertCategory stored procedure shown above as the source for the InsertCommand of the SqlDataAdapter. The @Identity output parameter will be reflected in the DataSet after the record has been inserted into the database when the Update method of the SqlDataAdapter is called. The code also retrieves the return value.

Modifying Data with Stored Procedures


Code - I
private static void ReturnIdentity(string connectionString) { using (SqlConnection connection = new SqlConnection(connectionString)) { // Create a SqlDataAdapter based on a SELECT query. SqlDataAdapter adapter = new SqlDataAdapter( "SELECT CategoryID, CategoryName FROM dbo.Categories", connection); // Create a SqlCommand to execute the stored procedure. adapter.InsertCommand = new SqlCommand("InsertCategory", connection); adapter.InsertCommand.CommandType = CommandType.StoredProcedure; // Create a parameter for the ReturnValue. SqlParameter parameter = adapter.InsertCommand.Parameters.Add( "@RowCount", SqlDbType.Int); parameter.Direction = ParameterDirection.ReturnValue; // Create an input parameter for the CategoryName. // You do not need to specify direction for input parameters. adapter.InsertCommand.Parameters.Add( "@CategoryName", SqlDbType.NChar, 15, "CategoryName"); // Create an output parameter for the new identity value. parameter = adapter.InsertCommand.Parameters.Add( "@Identity", SqlDbType.Int, 0, "CategoryID"); parameter.Direction = ParameterDirection.Output;

Modifying Data with Stored Procedures


Code - I
// Create a DataTable and fill it. DataTable categories = new DataTable(); adapter.Fill(categories); // Add a new row. DataRow categoryRow = categories.NewRow(); categoryRow["CategoryName"] = "New Beverages"; categories.Rows.Add(categoryRow); // Update the database. adapter.Update(categories); // Retrieve the ReturnValue. Int32 rowCount = (Int32) adapter.InsertCommand.Parameters["@RowCount"].Value; Console.WriteLine("ReturnValue: {0}", rowCount.ToString()); Console.WriteLine("All Rows:"); foreach (DataRow row in categories.Rows) { { Console.WriteLine(" {0}: {1}", row[0], row[1]); } } } }

How to get Last Inserted ID in MS SQL


Code

If your server supports the OUTPUT clause you could try this :
public static void CreateSocialGroup(string FBUID){ string query = "INSERT INTO SocialGroup (created_by_fbuid) " + " OUTPUT INSERTED.IDENTITYCOL VALUES (@FBUID)"; using (SqlConnection connection = new SqlConnection(ConnectionString)) { SqlCommand command = new SqlCommand(query, connection); command.Parameters.AddWithValue("@FBUID", FBUID); connection.Open(); var _id = command.ExecuteScalar(); } }

How to get Last Inserted ID in MS SQL


Code
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim UDOuting As AccessDataSource = CType(Page.FindControl("adsAllTs"), AccessDataSource) Dim tbDesc As TextBox = CType(gvHeaderUD.FooterRow.FindControl("tbDescAdd"), TextBox) Dim tbCourse As TextBox = CType(gvHeaderUD.FooterRow.FindControl("tbCourseAdd"), TextBox) Dim lblOIDAdd As Label = CType(Page.FindControl("lblOIDAdd"), Label) If tbDesc IsNot Nothing AndAlso tbCourse IsNot Nothing Then UDOuting.InsertParameters("Desc").DefaultValue = tbDesc.Text UDOuting.InsertParameters("Course").DefaultValue = tbCourse.Text UDOuting.Insert() Dim query As String = "SELECT @@IDENTITY Dim cmd As New Data.OleDb.OleDbCommand(query, CType(e.Command.Connection, Data.IDbConnection)) Dim newid As Integer = cmd.ExecuteScalar() End If End Sub

You might also like