C# 在一条语句中插入和选择

C# 在一条语句中插入和选择,c#,sql-server-2008,tsql,select,C#,Sql Server 2008,Tsql,Select,可能重复: 我有一张桌子缺勤 其中,ID是递增1的标识主键。 我正在从C语言的程序访问此表,我需要执行以下操作: 在缺勤姓名中插入职务值“aName”、“aJob” 问题是我需要同时获取插入的Id列,因为name和Job不是唯一的,所以我以后将无法检索该列 是否可以在该查询的Id列上添加select 更新 SqlConnection myConnection = new SqlConnection(@"SomeConnection"); myConnection.Open(); S

可能重复:

我有一张桌子缺勤

其中,ID是递增1的标识主键。 我正在从C语言的程序访问此表,我需要执行以下操作:

在缺勤姓名中插入职务值“aName”、“aJob”

问题是我需要同时获取插入的Id列,因为name和Job不是唯一的,所以我以后将无法检索该列

是否可以在该查询的Id列上添加select

更新

  SqlConnection myConnection = new SqlConnection(@"SomeConnection");
  myConnection.Open();
  SqlCommand myCommand = myConnection.CreateCommand();
  myCommand.CommandText = "Insert Into Absences (Name, Job) Values ('aName', 'aJob')";
  int currentAbs = (int)myCommand.ExecuteScalar();
我在ExecuteScalar行上得到一个错误。对象引用未设置为和对象的实例。

如果使用SqlCommand,则可以使用

int lastId = (int)command.ExecuteScalar();
检索插入记录的唯一id。 看一看。

SQL语句SCOPE\u IDENTITY将为您提供同一范围内新插入行的IDENTITY列的值

SqlConnection myConnection = new SqlConnection(@"SomeConnection");
myConnection.Open();
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = "Insert Into Absences (Name, Job) Values ('aName', 'aJob'); SELECT SCOPE_IDENTITY();";
int currentAbs = (int)myCommand.ExecuteScalar();

在此查询之后,您可以选择@@identity以获取mssql服务器中最后插入的id

一种方法是在插入记录后立即使用SELECT@@IDENTITY:

int id;
string query = "Insert Into Absences (Name, Job) Values ('aName', 'aJob')";
using (SqlCommand cmd = new SqlCommand(query, connection)) {
    connection.Open();
    // execute your INSERT query
    cmd.ExecuteNonQuery();
    // get the last-inserted ID
    cmd.CommandText = "SELECT @@IDENTITY";
    id = (int)cmd.ExecuteScalar();
}

所以这给了我最高的当前标识?不,因为最高标识不一定是插入的行。在同一行上给了我另一个异常。指定的强制转换无效。你能检查插入是否成功吗?@PhilMurray是的插入工作正常这听起来很像我需要的,尽管我如何从我的C程序访问它?哦,正是我需要的@PhaDaPhunk:很高兴帮助您:嗯,我得到的对象引用未设置为对象的实例。。我会把我的代码贴在上面,如果你能看一下的话,也许我没有用它right@PhaDaPhunk:哪一行显示此错误?请注意标识和范围。SCOPE\u标识更安全。按照解决方法中的建议使用输出子句。@HABO-这个错误在SQL 2008中也被确认了吗?@PhilMurray-AFAIK,它在2008年的生命周期中被修复了,但我还没有找到一个关于确切时间的声明。它被标记为Closed作为fixed。我将类型转换更改为Convert.ToInt32myCommand.ExecuteScalar;它成功了。。。知道为什么吗?
int id;
string query = "Insert Into Absences (Name, Job) Values ('aName', 'aJob')";
using (SqlCommand cmd = new SqlCommand(query, connection)) {
    connection.Open();
    // execute your INSERT query
    cmd.ExecuteNonQuery();
    // get the last-inserted ID
    cmd.CommandText = "SELECT @@IDENTITY";
    id = (int)cmd.ExecuteScalar();
}