简体   繁体   中英

Returning the row id from stored procedure in C#?

I'm trying to get the row id of a row that is inserted.

This is the Fuel class:

public class Fuel
{
    private Int32 fuelId;
    private DateTime fuelDate;

    public Fuel(DateTime fuelDate)
    {
        this.fuelDate = fuelDate;
    }

    public Fuel(Int32 fuelId, DateTime fuelDate)
    {
        this.fuelId = fuelId;
        this.fuelDate = fuelDate;
    }

    public Int32 FuelId() { return fuelId; }
    public DateTime FuelDate() { return fuelDate; }
}

This is the method that is trying to write to the database:

protected String connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;
        AttachDbFilename=" + "C:\\Users\\keith_000\\Documents\\Visual Studio 2017\\Projects\\RubberDress\\RubberDress\\Rubber.mdf" + ";" +
        "Integrated Security=True;" +
        "Connect Timeout=30";

public Int32 InsertFuelPurchase(Fuel myAddFuel)
{
        Int32 myFuelId;

        using (SqlConnection mySqlConn = new SqlConnection(connectionString))
        {
            mySqlConn.Open();

            using (SqlCommand myComm = new SqlCommand("FUELINSERT", mySqlConn))
            {
                myComm.CommandType = CommandType.StoredProcedure;
                myComm.Parameters.Add("@FUELDATE", SqlDbType.DateTime).Value = myAddFuel.FuelDate();
                myComm.Parameters.Add("@FUELID", SqlDbType.Int).Direction = ParameterDirection.Output;
                myFuelId = Convert.ToInt32(myComm.Parameters["@FUELID"].Value);
                mySqlConn.Close();
            }
        }

        return myFuelId;
    }

The stored procedure is

CREATE PROCEDURE [dbo].[FUELINSERT]
    @FUELDATE DATETIME,
    @FUELID INT OUTPUT
AS
    INSERT INTO FUELPURCHASE (FUELPURCHASEDATE)  
    VALUES (@FUELDATE)

    SELECT @FUELID = SCOPE_IDENTITY()

Which is writing to the following table

CREATE TABLE [dbo].[FUELPURCHASE] 
(
    [FUELPURCHASEID] INT IDENTITY (1, 1) NOT NULL,
    [FUELPURCHASEDATE] DATETIME NOT NULL

    PRIMARY KEY CLUSTERED ([FUELPURCHASEID] ASC)
);

Currently the result which is being returned is 0.

When I debug the method I find it 0 is being returned from the stored procedure.

Can anyone spot where I have to resolve the problem?

Of course you need to execute the command, ( ExecuteScalar , ExecuteNonQuery , even ExecuteReader will call the SP and runs your SqlCommand) but you don't need to have an out parameter, just SELECT SCOPE_IDENTITY() in the stored procedure and execute the command with ExecuteScalar

CREATE PROCEDURE [dbo].[FUELINSERT]
    @FUELDATE DATETIME
AS
    INSERT INTO FUELPURCHASE (FUELPURCHASEDATE) VALUES (@FUELDATE)
    SELECT SCOPE_IDENTITY()

Now you can call the SP with

....
using (SqlCommand myComm = new SqlCommand("FUELINSERT", mySqlConn))
{
    myComm.CommandType = CommandType.StoredProcedure;
    myComm.Parameters.Add("@FUELDATE", SqlDbType.DateTime).Value = myAddFuel.FuelDate();
    myFuelId = Convert.ToInt32(myComm.ExecuteScalar());
}
....

You are missing myComm.ExecuteNonQuery(); ...your code should looks like:

myComm.ExecuteNonQuery();
myFuelId = Convert.ToInt32(myComm.Parameters["@FUELID"].Value);

try this:

        mySqlConn.Open();
        using (SqlCommand myComm = mySqlConn.CreateCommand())
        {
            myComm.CommandType = CommandType.StoredProcedure;
            myComm.CommandText = "Exec YourProcedure @FUELDATE,@FUELID";
            myComm.Parameters.Add("@FUELDATE", SqlDbType.DateTime).Value = myAddFuel.FuelDate();
            myComm.Parameters.Add("@FUELID", SqlDbType.Int).Direction = ParameterDirection.Output;
            myFuelId = Convert.ToInt32(myComm.Parameters["@FUELID"].Value);
            int result = myComm.ExecuteNonQuery();

            mySqlConn.Close();
            return result;

        }

when returning a single value use myComm.ExecuteScalar()

It is depend on your FUELDATE, FUELID position:

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