SQL获取新插入行的标识数

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值