简体   繁体   中英

Returning the ID of a new record

I'm green as it can be with the use of both C# and store procedures so this has been a real learning experience but I'm almost there. I've got two stored procedures (The first one calls the second one then completes after the second one has finished and returns the document ID ... 'DID' of the newly created record) that are working just fine in testing outside of my C# code.

This is intended to be called from my ASP.NET web project code behind C# page and I'm basing most of my logic of a Microsoft KB article ( kb#320916 ). If you look at the bottom code segment there you'll see the section that I'm pulling my reference from.

As I was working thorough this it was making perfect sense until I get to the part where they are pulling back a dataset with multiple record and I thought to myself 'uh oh, I'm in trouble here!' because I just have one value I need back and do not expect or want more than that single value returned. Just that record id. Here is what I have thus far:

SqlConnection GETTNewDocs = new SqlConnection("server = gbaptccsr01; database = ARFS; Integrated Security=True");
SqlDataAdapter InsertANewDoc = new SqlDataAdapter("putthedatain", GETTNewDocs);
InsertANewDoc.SelectCommand.CommandType = CommandType.StoredProcedure;
InsertANewDoc.SelectCommand.Parameters.Add(new SqlParameter("@EventID", SqlDbType.VarChar(50)));
InsertANewDoc.SelectCommand.Parameters["@EventID"].Value = (EleIDLBL.Text).Trim();
InsertANewDoc.SelectCommand.Parameters.Add(new SqlParameter("@AltSub", SqlDbType.Int));
InsertANewDoc.SelectCommand.Parameters.["@AltSub"].Value = (Convert.ToInt32(Session["AltSubDocIdx"])+5);
InsertANewDoc.SelectCommand.Parameters["@DID"].Direction = ParameterDirection.Output;

The stored procedure itself that is being called and returning the data looks like this:

CREATE PROCEDURE [dbo].[NewGETTDoc]
@EventID VARCHAR(50),
@AltSub int,
@DocName VARCHAR(512) = "New",
@new_identity int = NULL OUTPUT,
@param1 VARCHAR(50) = @EventID
AS BEGIN
SET NOCOUNT ON;

INSERT dbo.GETT_Documents(EID, alt_sub_idx, DocName )SELECT @EventID, @AltSub, @DocName;
SET @new_identity = SCOPE_IDENTITY();

EXEC UpdateSubIdx @param1 
END

There is an error in your code and some better practices could be used here.

First (the error), you should name the parameters exactly as the Stored Procedure expects them to be named and use the correct syntax to build them (SqlDbType.NVarChar(50) will be mistakenly interpreted as a call to a method named NVarChar in the SqlDbType class???)

Second, you don't need an SqlDataAdapter. You are just inserting a new row thus there is no need to use a class specifically built to return records. A simple SqlCommand will do.

Third, disposable objects should be disposed with the using statement

using(SqlConnection con  = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand("NewGETTDoc", con))
{
    con.Open();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@EventID", SqlDbType.VarChar, 50).Value = EleIDLBL.Text.Trim();
    cmd.Parameters.Add("@AltSub", SqlDbType.Int).Value = Convert.ToInt32(Session["AltSubDocIdx"])+5;
    SqlParameter p = cmd.Parameters.Add("@new_identity", SqlDbType.Int)
    p.Direction = ParameterDirection.Output;
    int rowsAffected = cmd.ExecuteNonQuery();
    if(rowsAffected > 0)
    {
       int newID = Convert.ToInt32(p.Value); 
       ... do your task with the newID ....
    }
}

It's tricky to say because of the incomplete code so I'm shooting in the dark with this, but try removing this line (because the SP has no parameter called @DID);

InsertANewDoc.SelectCommand.Parameters["@DID"].Direction = ParameterDirection.Output;

And add these;

InsertANewDoc.SelectCommand.Parameters.Add(new SqlParameter("@new_identity", SqlDbType.Int));
InsertANewDoc.SelectCommand.Parameters.["@new_identity"].Direction = ParameterDirection.Output;

After the database call you can get the new ID in your C# with this;

int newID = int.Parse(InsertANewDoc.SelectCommand.Parameters.["@new_identity"].Value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM