2012-09-17 24 views
1

如果傳入的參數值爲空,如何創建不更新列的批量更新?例如:在Java中執行SQL批量更新時,如果傳入參數parm不會更新字段

String UPDATE_STMT = "UPDATE MY_TABLE SET col1 = ?, col2 = ?, col3 = ?"; 
Connection conn = getConnection(); 
PreparedStatement pstmt = conn.preparedStatement(UPDATE_STMT); 

List items = getItems(); 
for (ItemType item : items) { 

    stmt.setString(1, item.x); 
    stmt.setString(2, item.y); 
    stmt.setString(3, item.z); 
} 

pstmt.executeBatch(); 

如何編碼它,以便col1只會更新item.x的值,如果item.x不爲null或爲空?如果item.x爲空/空,我不希望col1字段中的當前值被覆蓋。這是針對Oracle 10g數據庫的。

回答

0

使用COALESCE返回COL1如果item.x爲null:

String UPDATE_STMT = "UPDATE MY_TABLE SET col1 = COALESCE(?,col1), col2 = ?, col3 = ?" 

然後,您只需確保item.x始終爲空,而不是空白字符串。

+0

這樣做,即使col1爲空? – wlaem

+0

如果參數全爲空,則COALESCE返回null。 – Jim

1

我想它應該爲你工作:

String UPDATE_STMT = "UPDATE MY_TABLE SET col1 = 
CASE WHEN ? IS NULL THEN col1 ELSE ? END, col2 = ?, col3 = ?"; 

注意,現在你需要設置item.x兩次,stmt.setString(1, item.x); stmt.setString(2, item.x);

0

如果你不想要alex07's Oracle specific solution,只需重新生成每個項目集的準備好的語句。

Connection conn = getConnection(); 

List items = getItems(); 
for (ItemType item : items) { 

    String UPDATE_STMT = "UPDATE MY_TABLE SET "; 
    if (item.x != null) {UPDATE_STMT += "col1 = ?, ";} 
    UPDATE_STMT += "col2 = ?, col3 = ?"; 

    PreparedStatement pstmt = conn.preparedStatement(UPDATE_STMT); 

    int count = 0; 
    if (item.x != null) {pstmt.setString(++count, item.x);} 
    pstmt.setString(++count, item.y); 
    pstmt.setString(++count, item.z); 

    pstmt.executeBatch(); 
}