尝试通过SQL从另一个表中获取ID来插入访问数据库

时间:2013-06-19 16:37:07

标签: c# ms-access-2010 sql-insert

我在Access数据库中有2个表:

  • tblMachine
  • 字段:
  • 机号
  • MachineDescription

  • tblProblem

  • 字段
  • ProblemID
  • 机号
  • ProblemDescription

我正在尝试将新记录添加到tblProblem中,使用MachineDescription从tblMachine中查找MachineID

但是,我的SQL语句会在子选择语句

上抛出错误

以下是我的发言:

string sql = "INSERT INTO tblProblem" +
                " ([MachineID], [ProblemDescription], [ProblemOrder])" +
                " VALUES (" + 
                "(SELECT ([MachineID] FROM tblMachine WHERE MachineDescription = @MachineDescription))," +
                " @ProblemDescription, @ProblemOrder);";

突出显示的问题是这部分:

"(SELECT ([MachineID] FROM tblMachine WHERE MachineDescription = @MachineDescription)),"

我做错了吗?它告诉我语法错误...

1 个答案:

答案 0 :(得分:1)

额外的括号,也许是不合格的字段名称:

String sql = "INSERT INTO tblProblem " + 
    "([MachineID], [ProblemDescription], [ProblemOrder])" +
    "SELECT tblMachine.[MachineID], @ProblemDescription, @ProblemOrder " +
    "FROM tblMachine " +
    "WHERE tblMachine.MachineDescription = @MachineDescription";