已经有人发过类似问题:http://topic.csdn.net/t/20040722/13/3199585.html
public   int   GetCurrentIndentity()   
  {   
  int   indentity=0;   
  //@@IDENTITY   
  string   str="select   @@identity";   
  try   
  {   
    SqlCommand   com=new   SqlCommand(str,CDatabase.Connect);   
    indentity=(int)com.ExecuteScalar();<---出错指定的转换无效???   
  }   
  catch(SqlException   ee)   
  {   
    this.ErrorMessage=ee.Message;   
  }   
    return   indentity;   
  } 结论是这种情况是必须得用Convert.ToInt32()来解决,原因是什么呢?select   @@identity出来的也是数字啊
假如ExecuteScalar是用泛型实现的,就像这样public T ExecuteScalar<T>()
{
           
            T temp = default(T);            object obj = this.ExecuteScalar();
            if ((obj == null) || (obj == DBNull.Value))
            {
                return temp;
            }
            temp = (T)obj;
            return temp;
}
这时候如果数据库里返回的是select   @@identity,调用时T是int,当然还是会出现“指定的转换无效”的错误了,
这时是不是只能用typeof(T)来特别判断一下T是System.Int32的情况了?有更好的办法吗?

解决方案 »

  1.   

    (int)com.ExecuteScalar();如果原型不是int32 的话当然报错。还是Convert适应性强。因为数值型还有好几种类型呢。
      

  2.   

    select  @@identity上在返回是空..
    和Insert一起使才有效果..
    单独执行返回NULL所以报错是正常的.
      

  3.   


    可以通过判断com.ExecuteScalar()的返回值类型来做具体的操作.. int intValue = 0;
                SqlConnection conn = new SqlConnection(@"Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=db1;Data Source=.");
                SqlCommand com = new SqlCommand("select @@IDENTITY;",conn);
                conn.Open();
                object o = com.ExecuteScalar();
                if (o.GetType().FullName == "System.DBNull")
                {
                    intValue = -1;
                }
                else if (o.GetType().FullName == "System.Int32")
                {
                    intValue = Convert.ToInt32(o);
                }
                else { 
                //...
                }
                conn.Close();
                conn.Dispose();
      

  4.   

    你的那句 sql string  str="select  @@identity"; 只会返回 NULL,因为没有执行插入或者其他语句来生成 identityobject o = com.ExecuteScalar();
    if(o != DBNull.Value) {
    return (int)o;
    }
      

  5.   

    select  @@identity   必须与Insert一起使用,作用是取得你刚刚添加的这条纪律的主键