Can't get value??

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....
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top