如何获得最后一排的插入到表的主键 [英] How to get the primary key of the last row inserted into the table

查看:106
本文介绍了如何获得最后一排的插入到表的主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的多视图索引中插入的消息的详细信息。在第一种观点的用户可以单击Next按钮进入新闻细节,然后插入到数据库
第二种观点提供了一个用户添加的是新闻图片(只​​允许3图像),

什么我有问题是,第一个视图将数据插入表dbo.newsdetail具有主键
NewSID的,而第二种观点应该添加使用的消息NewSID的只是加入newsimages表尊敬的图像。我只是不知道如何让细节的NewSID的
这是在第一种观点的新闻ID是工作作为这两个表​​的外键添加。任何帮助或建议将是非常美联社preciated。

 的静态公共无效insertNews(字符串newsDescription,串newsImage,串newsTitle)
{
    康涅狄格州的SqlConnection =新的SqlConnection(ConnectionString中);
    conn.Open();
    的SqlCommand insertNews =新的SqlCommand(INSERT INTO caravanNews(newsDescription,newsImage,newsTitle)VALUES('+ newsDescription +,+ newsImage +,+ newsTitle +'),conn);在
    insertNews.ExecuteNonQuery();
    conn.Close();}


解决方案

一个单独的SQL语句

  SELECT SCOPE_IDENTITY()

或者

OUTPUT子句

 插入MyTable的(... =
输出INSERTED.KeyCol
VALUES(...)--Or SELECT ...从另一个表)

编辑:


  • 改变你的插入语句来匹配雷

  • .ExecuteNonQuery()改为等等= xxx.ExecuteScalar()

I am using multiview index to insert the news details. In the first view the user can enter details of news which is then inserted into db on clicking the next button the second view gives a user to add images of that news (only 3 images allowed) ,

what I am having problem is that the first view inserts data into the table dbo.newsdetail with a primary key newsID , while the second view should add the respected images using that newsId of the news just added into newsimages table. I just dont know how to get the newsID of the details which is added in the first view as news Id is working as a foreign key for the both the table. Any help or suggestions will be highly appreciated .

 static public void insertNews(string newsDescription, string newsImage, string newsTitle)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    conn.Open();
    SqlCommand insertNews = new SqlCommand("Insert INTO caravanNews(newsDescription, newsImage, newsTitle) VALUES ('" + newsDescription + "', '" + newsImage + "' , '" + newsTitle + "')",conn);
    insertNews.ExecuteNonQuery();
    conn.Close();

}

解决方案

A separate SQL statement

SELECT SCOPE_IDENTITY()

Or the OUTPUT clause

INSERT MyTable (...=
OUTPUT INSERTED.KeyCol
VALUES (...) --Or SELECT ... FROM Another table)

Edit:

  • change your insert statement to match mine
  • change .ExecuteNonQuery() to blah = xxx.ExecuteScalar()

这篇关于如何获得最后一排的插入到表的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆