insert into mcc_InterShow(C_ShowerName,T_Mark) values('asdf','asdfasdf') select @@identity as ID--此句用于返回插入记录的ID号(ID为自增长型)请问如何接收上面Sql语句中由select @@identity as ID 返回的值
cmd.ExecuteNonQuery()不行,返回的只是受影响的行数
cmd.ExecuteReader()也不行,报错 在没有任何数据时进行无效的读取尝试
谢谢

解决方案 »

  1.   

    SqlCommand cmd = new SqlCommand(@"insert into xxx (a,b,c) values(@a,@b,@c)
    select SCOPE_IDENTITY()", conn);
    cmd....object o = cmd.ExecuteScallar();
    int newId = (int) o;
      

  2.   

    用SqlDataAdapterSqlDataAdapter myDataAdapter = new SqlDataAdapter("存储过程",myConnection);
    myDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;DataSet ds = new DataSet();
    myDataAdapter.Fill(ds);
    return ds;
      

  3.   

    另外,使用 @@identity 在分布式环境中会有问题。 不要用这个,改用 SCOPE_IDENTITY()
      

  4.   

    刚刚调试通过的代码:using System;
    using System.Data;
    using System.Data.SqlClient;namespace DbConsoleDemo
    {
    /// <summary>
    /// InsertDemo 的摘要说明。
    /// </summary>
    public class InsertDemo
    {
    public InsertDemo() {} public static void Test1() {
    SqlConnection conn = new SqlConnection(Config.RChenConnection);

    using (conn) {
    SqlCommand cmd = new SqlCommand(@"insert into IdStore(nextid) values (@nextid)
    select SCOPE_IDENTITY()", conn);
    cmd.Parameters.Add("@nextid", 123);
    conn.Open();
    object o = cmd.ExecuteScalar();
    int newId = Convert.ToInt32(o);
    Console.WriteLine("新的 id 是:{0}", newId);
    conn.Close();
    }
    Console.ReadLine();
    }
    }
    }
      

  5.   

    现在 csdn 回帖里面的缩进格式不知道为什么会丢失,郁闷~