查询值和目标字段的数量不同(联盟)

时间:2017-06-05 00:51:51

标签: sql ms-access

遇到此SQL错误 - 查询值和目标字段的数量不同(Union)。使用Access数据库。 programList表中只有两个字段 - userID和programID。在我的cs文件中使用参数。这是完整的方法:

public void AddProgramList (string program, int userID)
{
    dbConnection.Open();

    string sqlStmt = "INSERT INTO programs (program) ";
    sqlStmt += "VALUES (@program)";
    string sqlStmt2 = "INSERT INTO programList (userID, programID) " +
                      "SELECT userID " +
                      "FROM users" +
                      "WHERE userID = @userID " +
                      "UNION " +
                      "SELECT programID " +
                      "FROM programs" +
                      "WHERE program = @program;";

    OleDbCommand dbCommand = new OleDbCommand(sqlStmt, dbConnection);

    OleDbParameter param = new OleDbParameter("@program", program);

    dbCommand.Parameters.Add(param);

    dbCommand.Parameters.Add(new OleDbParameter("@userID", userID));

    OleDbCommand dbCommand2 = new OleDbCommand(sqlStmt2, dbConnection);

    OleDbParameter param2 = new OleDbParameter("@program", program);

    dbCommand2.Parameters.Add(param2);

    dbCommand2.Parameters.Add(new OleDbParameter("@userID", userID));


    dbCommand.ExecuteNonQuery();

    dbCommand2.ExecuteNonQuery();

    dbConnection.Close();
}

1 个答案:

答案 0 :(得分:1)

如果你打印出SQL,你会看到:

INSERT INTO programList (userID, programID) " +
SELECT userID FROM usersWHERE userID = @userID UNION SELECT programID FROM programsWHERE program = @program;

错误应该非常明显。您可能没有名为usersWHERE的表格。

当我看到问题时,您正在尝试插入两个列。所以,我想你打算:

INSERT INTO programList (userID, programID)
    SELECT userID, programID
    FROM users, programs
    WHERE userID = @userID AND program = @program;

或者更简单:

INSERT INTO programList (userID, programID)
    SELECT @userID, programid
    FROM programs
    WHERE program = @program;