是否可以进行批量更新?

时间:2009-06-29 21:13:31

标签: c# sql sqlite

是否可以批量更新?我做了一个构建插入,现在我想更新每个用户ID以增加计数。

以下是我的构建插入示例

void updateMediaForSubscribers(long userId, long mediaId, Media_Base.Catagory cat, DateTime currentDate)
{
    command.CommandText =
        "INSERT INTO user_media_subscription (recipientId, mediaId, catagory) " +
        "SELECT watcher, @mediaId, @category " +
        "FROM user_watch WHERE watched=@watched;";
    command.Parameters.Add("@mediaId", DbType.Int64).Value = mediaId;
    command.Parameters.Add("@category", DbType.Int64).Value = cat;
    command.Parameters.Add("@watched", DbType.Int64).Value = userId;
    command.ExecuteNonQuery();

    //now I want to increase but this syntax is wrong
    //currently near "LEFT": syntax error
    //this is made up and shouldn't work.
    command.CommandText =
        "UPDATE user_data SET mediaMsgCount=mediaMsgCount+1 " +
        "LEFT JOIN user_watch AS w ON w.watcher=user_data.userId " +
        "WHERE w.watched=@watched;";
    command.Parameters.Add("@watched", DbType.Int64).Value = userId;
    command.ExecuteNonQuery();
}

2 个答案:

答案 0 :(得分:1)

您需要使用“UPDATE ... WITH”

UPDATE ud SET ud.mediaMsgCount = ud.mediaMsgCount + 1
FROM user_data ud LEFT JOIN user_watch uw ON uw.watcher = ud.userId
WHERE uw.watched = @watched

查看http://www.bennadel.com/blog/938-Using-A-SQL-JOIN-In-A-SQL-UPDATE-Statement-Thanks-John-Eric-.htm

答案 1 :(得分:1)

试试这个SQL:

UPDATE user_data 
   SET mediaMsgCount = mediaMsgCount+1 
  FROM user_data 
  LEFT JOIN user_watch AS w ON w.watcher=user_data.userId 
 WHERE w.watched=@watched