方法一:
insert into table() values();select IDENT_CURRENT ('tableName')
执行此SQL语句返回得就是新记录的主键值
SQLDataReader sr;
....
return sr[0]
方法二:
string strSql = "INSERT INTO TableName(zd1,zd2,...) VALUES(@zd1,@zd2,...); select @@ IDENTITY AS 'Identity'";
SqlConnection Conn = new SqlConnection(strConnection);
SqlCommand Cmm = new SqlCommand(strSql,Conn);
Cmm.Parameters.Add(@zd1,SqlDbType.字段类型,{size});
Cmm.Parameters["@zd1"].value = 插入值;
Cmm.Parameters.Add(@zd2,SqlDbType.字段类型,{size});
Cmm.Parameters["@zd2"].value = 插入值;
int intID = 0 ;
try
{
Conn.Open();
intID = Convert.ToInt32(Cmm.ExecuteScalar());
}
catch(Exception ex)
{
//报错语句
}
finally
{
if(Conn.State = ConnectionState.Open);
Conn.Close();
}
Response.Write("新增记录的ID号为:"+ intID.ToString());
Response.End();