您的位置:首页 > 数据库

SQL获取新插入行的标识数

2010-08-26 09:27 204 查看
对数据库操作时,需要保留刚插入的新行的标识列以备后用,下面是用SQL语句实现方法:
private SqlConnection connection;
//连接字符串
this.connection = new SqlConnection();
this.connection.ConnectionString =
                       @"Data Source=.;Initial Catalog=DBDemo;Persist Security Info=True;User ID=sa;Password=123";
this.connection.Open();
 
//SQL语句
SqlCommand command = new SqlCommand();
command.Connection = this.connection;
command.CommandType = CommandType.Text;
string sql = string.Format(
                            "insert into ……");
command.CommandText = sql;
 
//执行SQL语句
command.ExecuteNonQuery();
 
//获取标识列的SQL语句
string sequel = "SELECT @@IDENTITY"; //主要是这句
SqlCommand comm = new SqlCommand();
comm.Connection = this.connection;
comm.CommandType = CommandType.Text;
comm.CommandText = sequel;
 
//执行SQL语句,获取新插入行的标识列
object id = comm.ExecuteScalar();
 
介绍@@IDENTITY的文章可以从下面找到
http://baike.baidu.com/view/1592444.htm
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息