tags:

views:

230

answers:

2

Is it possible to bulk update? I did a build insert, now I would like to update each of the user IDs to increase the count.

Here's a sample of my build insert

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();
}
+1  A: 

You need to use "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

Take a look at http://www.bennadel.com/blog/938-Using-A-SQL-JOIN-In-A-SQL-UPDATE-Statement-Thanks-John-Eric-.htm

Kragen
near "FROM": syntax error :(
acidzombie24
Hmm, I've tweaked it, but I dont have SQL server locally to test it - downloading it now so I'll be able to make sure it works in a bit :-)
Kragen
I think the problem with this code is that you cannot use an alias in the UPDATE clause.
jn29098
+1  A: 

Try this 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
jn29098