Can't get value??

  • Thread starter Thread starter Calvin Lai
  • Start date Start date
C

Calvin Lai

Hi all,

I am using a SqlCommand to perform an insert statement, after which to
return the ID (Idnetity field). However, it doesn't seem to work. Following
is the code which doesn't work. Can anyone point me where I did wrong?
Thanks.

int myID = 0;
string strSQL = "INSERT INTO TABLE1 (TextField1) VALUES (@TextField1);SELECT
@ID=@@Identity";
oSqlCmd = new SqlCommand(strSQL, oConnection);

SqlParameter parm = new SqlParameter("@TextField1", SqlDbType.NVarChar);
parm.Value = "test";
oSqlCmd.Parameters.Add(parm);

parm = new SqlParameter("@ID", SqlDbType.Int);
parm.Value = myID;
parm.Direction = ParameterDirection.Output;
oSqlCmd.Parameters.Add(parm);

oSqlCmd.ExecuteNonQuery();



after the code, it was successfully inserted. But the myID always showing
0....
 
Hi all,

I am using a SqlCommand to perform an insert statement, after which to
return the ID (Idnetity field). However, it doesn't seem to work. Following
is the code which doesn't work. Can anyone point me where I did wrong?
Thanks.

int myID = 0;
string strSQL = "INSERT INTO TABLE1 (TextField1) VALUES (@TextField1);SELECT
@ID=@@Identity";
oSqlCmd = new SqlCommand(strSQL, oConnection);

SqlParameter parm = new SqlParameter("@TextField1", SqlDbType.NVarChar);
parm.Value = "test";
oSqlCmd.Parameters.Add(parm);

parm = new SqlParameter("@ID", SqlDbType.Int);
parm.Value = myID;
parm.Direction = ParameterDirection.Output;
oSqlCmd.Parameters.Add(parm);

oSqlCmd.ExecuteNonQuery();

after the code, it was successfully inserted. But the myID always showing
0....

You don't need to set myID beforehand - you need to look at it
afterwards.

Just doing

parm.Value = myID;

doesn't associate the parameter with the variable myID at all - it just
sets the value to be the current value of myID.
 
Back
Top