现在的位置: 首页 > 综合 > 正文

SQL获取新插入行的标识数

2013年12月03日 ⁄ 综合 ⁄ 共 807字 ⁄ 字号 评论关闭

对数据库操作时,需要保留刚插入的新行的标识列以备后用,下面是用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

 

抱歉!评论已关闭.