Sunday, February 26, 2012

Getting identity

Hi
Trying to get a return value from this code, but only gets a 0. Am using SQLExpress.
SqlParameter[] p =newSqlParameter[4];
p[0] =newSqlParameter("@.a","aaa");
p[1] =newSqlParameter("@.b","bbb");
p[2] =newSqlParameter("@.c","ccc");
p[3] =newSqlParameter("@.d",SqlDbType.Int, 40);
p[3].Direction =ParameterDirection.ReturnValue;

string s =@."set nocount on INSERT INTO ABC(A, B, C) VALUES(@.a,@.b,@.c) SELECT scope_identity()";

using(SqlConnection conn =newSqlConnection(this._connection))
{
conn.Open();
SqlHelper.ExecuteNonQuery(conn,CommandType.Text, s, p);
int foo = p[3].Value;
}

You are trying to execute 2 sql statements without separating them. Add a semi-colon to the statement after the VALUES (stuff), like this (shown in blue):

string s =@."set nocount on INSERT INTO ABC(A, B, C) VALUES(@.a,@.b,@.c); SELECT scope_identity()";

|||Your not setting your parameter to anything. Update your select to SELECT @.d = scope_identity()

Nick|||DarrellNorton :No, didn't do any good.
Nick:Will test it now.|||Both of your answers combine did the trick. Plus that I had to have ParameterDirection.Output.
Thanks for your answers.
Working code.
SqlParameter[] p =newSqlParameter[4];
p[0] =newSqlParameter("@.a","aaa");
p[1] =newSqlParameter("@.b","bbb");
p[2] =newSqlParameter("@.c","ccc");
p[3] =newSqlParameter("@.d",SqlDbType.Int, 40);
p[3].Direction =ParameterDirection.Output;

string s =@."set nocount on INSERT INTO ABC(A, B, C) VALUES(@.a,@.b,@.c); SELECT @.d = scope_identity()";

using(SqlConnection conn =newSqlConnection(this._connection))
{
conn.Open();
SqlHelper.ExecuteNonQuery(conn,CommandType.Text, s, p);
int foo = p[3].Value;
}

No comments:

Post a Comment