ADO.net里面我如何插入一个记录后立即得到它的主键值

payaqa 2004-08-20 08:24:34
比如有个叫student的表,主键叫stid,如果我用SqlCommand.ExecuteNonQuery()插入一条新纪录以后,如何能够立即得到刚插入的这条记录的stid(即主键)的值?

谢谢。
...全文
183 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
marvelstack 2004-08-20
  • 打赏
  • 举报
回复
参考多表更新,输出参数。
http://blog.csdn.net/zhzuo/archive/2004/08/06/67037.aspx
payaqa 2004-08-20
  • 打赏
  • 举报
回复
谢谢各位,是加Identity,不加不可以直接用ExecuteNonQuery()
siugwan 2004-08-20
  • 打赏
  • 举报
回复
在insert语句后加入
;select @@identity as mynewid
执行时用
int newid = Convert.ToInt32(cmd.ExecuteScalar());
zhpsam109 2004-08-20
  • 打赏
  • 举报
回复
在ORACLE中如果你使用的是序列,可以使用seqname.Currval来取得!
zhpsam109 2004-08-20
  • 打赏
  • 举报
回复
IDENT_CURRENT
返回为任何会话和任何作用域中的指定表最后生成的标识值。

语法
IDENT_CURRENT('table_name')

参数
table_name

是将要返回其标识值的表的名称。table_name 的数据类型为 varchar,没有默认值。

返回类型
sql_variant

注释
IDENT_CURRENT 类似于 Microsoft® SQL Server™ 2000 标识函数 SCOPE_IDENTITY 和 @@IDENTITY。这三个函数都返回最后生成的标识值。但是,它们在定义"最后"的作用域和会话上不同。

IDENT_CURRENT 返回为任何会话和任何作用域中的特定表最后生成的标识值。


@@IDENTITY 返回为当前会话的所有作用域中的任何表最后生成的标识值。


SCOPE_IDENTITY 返回为当前会话和当前作用域中的任何表最后生成的标识值。
示例
下面的示例说明由 IDENT_CURRENT、@@IDENTITY 和 SCOPE_IDENTITY 返回的不同的标识值。

USE pubs
DROP TABLE t6
DROP TABLE t7
GO
CREATE TABLE t6(id int IDENTITY)
CREATE TABLE t7(id int IDENTITY(100,1))
GO
CREATE TRIGGER t6ins ON t6 FOR INSERT
AS
BEGIN
INSERT t7 DEFAULT VALUES
END
GO
--end of trigger definition

SELECT * FROM t6
--id is empty.

SELECT * FROM t7
--id is empty.

--Do the following in Session 1
INSERT t6 DEFAULT VALUES
SELECT @@IDENTITY
/*Returns the value 100, which was inserted by the trigger.*/

SELECT SCOPE_IDENTITY()
/* Returns the value 1, which was inserted by the
INSERT stmt 2 statements before this query.*/

SELECT IDENT_CURRENT('t7')
/* Returns value inserted into t7, i.e. in the trigger.*/

SELECT IDENT_CURRENT('t6')
/* Returns value inserted into t6, which was the INSERT statement 4 stmts before this query.*/

-- Do the following in Session 2
SELECT @@IDENTITY
/* Returns NULL since there has been no INSERT action
so far in this session.*/

SELECT SCOPE_IDENTITY()
/* Returns NULL since there has been no INSERT action
so far in this scope in this session.*/

SELECT IDENT_CURRENT('t7')
/* Returns the last value inserted into t7.*/

wangsaokui 2004-08-20
  • 打赏
  • 举报
回复
@@IDENTITY
BearRui 2004-08-20
  • 打赏
  • 举报
回复
不要用ExecuteNonQuery(),直接用下面的试一下!!!
int id=(int) SqlCommand.ExecuteScalar();
payaqa 2004-08-20
  • 打赏
  • 举报
回复
SQL Server啊
epimetheus 2004-08-20
  • 打赏
  • 举报
回复
什么数据库?

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧