2017-06-05 138 views
0

遇到此SQL錯誤 - 查詢值和目標字段的數量不相同(Union)。使用Access數據庫。 programList表中只有兩個字段 - userID和programID。在我的cs文件中使用參數。下面是完整的方法:查詢值和目標字段的數量不相同(Union)

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

如果打印出來的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; 
+0

是的,我是一個大假 –

+0

@JohnVinson。 。 。一點也不。但是,即使在執行代碼之前,您也應該學會打印字符串。畢竟,你希望它是正確的,驗證是最好的保險。 –

+0

嗯,修正了間距問題,仍然收到錯誤 –

相關問題