質問

I have a stored procedure that looks like so.

ALTER PROCEDURE dbo.addPackage(

    @PackageStatus                      VARCHAR(50) = null,
    @OrgCode                            VARCHAR(50) = null,
    @SystemID                           VARCHAR(50) = null,
    @ID                               int OUTPUT
)
AS
BEGIN
    insert into package_table
    (
            PackageStatus,
            OrgCode,
            SystemID
            )
            values
            (@PackageStatus, 
            @OrgCode, 
            @SystemID
            )
            SET @ID =  SCOPE_IDENTITY()
END

And my function adds the following parameters to the sql command and calls sqlCommand.ExecuteNonQuery();

List<SqlParameter> parameters = new List<SqlParameter>();

parameters.Add(new SqlParameter("@PackageStatus", package.PackageStatus));
parameters.Add(new SqlParameter("@OrgCode", package.OrgCode));
 parameters.Add(new SqlParameter("@SystemID", package.SystemID));

SqlParameter outParameter = new SqlParameter("@ID", SqlDbType.Int);
outParameter.Direction = ParameterDirection.Output;
parameters.Add(outParameter);

but I keep getting a 0 back from the stored porcuedure evne though I have an out parameter declared and set it before the stored procedure exits. The record is successfully added with the auto incrementing value for the ID but the ID is not returned when I get the output parameter back. It is set to 0.

Any suggestions?

役に立ちましたか?

解決

You've defined the output parameter - but do you also read it out after your call to .ExecuteNonQuery() ?? Unfortunately, you're not showing that code...

Basically, you need

SqlCommand cmd = new SqlCommand(..., connection); .....

// set up your parameter as above

connection.Open();
cmd.ExecuteNonQuery();

var outputValue = cmd.Parameters["@APID"].Value;  // you need to read it out!

connection.Close();

Are you doing this?? And that's where you're getting 0 back all the time??

The output parameter is NOT the return value from the .ExecuteNonQuery() call - you need to explicitly read out the parameter value after the call.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top