【问题标题】:Read last Inserted row in Sql according to its Time stamp根据时间戳读取Sql中最后插入的行
【发布时间】:2012-06-05 00:34:03
【问题描述】:

sql 有一个名为 emp 的表。

emp(emp_id int IDENTITY primary key, EmployeeName varchar(50),.......)

我想在上面的表格中插入一条记录。这是我在 asp.net 中的代码。

DBconnection dbcon = new DBconnection();
string query = "insert into emp values('" + TextBox_EmpName.Text + "','" + ....);
int no1 = dbcon.insertQuery(query);

我有另一个名为 emp-relation 的表

 emp-relation(emp_id int primary key, count int, ....) 
     -- foreign key (emp_id)references emp(emp_id)

我的问题是当我插入 emp 行时,我不知道emp_id 是什么,因为它是由自动创建的。当我要插入 emp-relation 时,我想得到 emp-id 因为它是外键。

我该怎么做?有没有办法根据时间戳或其他东西读取Sql中的最后一个插入行?我相信记录本质上不是根据插入的时间戳进行排序的。请帮帮我。

【问题讨论】:

    标签: asp.net sql-server identity


    【解决方案1】:

    基本上有两种方法。第一种方法是从第一个插入查询中返回新 ID:

    insert into emp values(...)
    select scope_identity() as NewID
    

    第二种方法是在插入关系表时查找第一行:

    insert  emp-relation
            (emp_idm, ...) 
    select  emp_id
    ,       ...
    from    emp
    where   emp_name = @EmpName
    

    您必须传入足够多的列以使引用唯一。

    【讨论】:

    • 谢谢安多玛。您的第二种方式:如果有多个记录使用相同的 EmpName。这不是要工作吗?你能解释一下你的第一种方式吗?
    • 对,where 子句必须只返回一行,所以如果 EmpName 不是 unqiue,您将需要更多行。 scope_identity() 返回最后插入的 identity 值。您可以在客户端代码中读回它并在第二个查询中使用它。
    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 2021-01-10
    • 1970-01-01
    • 2012-03-28
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多