Why won't this SQL output parameter play nicely?

683 Views Asked by At

I have the following code. When I use breakpoints, I can see that ["@myID"].Value is a real value, such as 2467. However, I'm not able to cast that as a string for my tryParse. I've tried using "as string" like below, and I've also tried toString(). My stringID remains null, so the tryParse leaves the myID value as a zero. I'm sure it's a trivial syntax issue, but I'm stumped. I need to return a real ID such as 2467, etc.

public static int myMethod(string name)
{
    Database myDB = DatabaseFactory.CreateDatabase("myDatabase");
    DbCommand myCommand = myDB.GetStoredProcCommand("myStoredProc");

    myDB.AddInParameter(myCommand, "@Name", DbType.String, name);
    myDB.AddOutParameter(myCommand, "@myID", DbType.Int32, 4);

    int myID = 0;

    int test = myDB.ExecuteNonQuery(myCommand);
    string stringID = myCommand.Parameters["@myID"].Value as string;
    bool canParse = int.TryParse(stringID, out myID);
    return myID;
}
2

There are 2 best solutions below

1
On BEST ANSWER

My guess is that the cast is failing. You are declaring the OUT param as INT, you should attempt to read it back as int as well:

int stringID =(int) myCommand.Parameters["@myID"].Value ;

And I don't think you need to attempt to parse it again on the next line. myCommand.Parameters["@myID"].Value should already contain the value.

0
On

Also you can use "Convert.ToInt32" function

int stringID = Convert.ToInt32(myCommand.Parameters["@myID"].Value) ;