views:

44

answers:

2

Hi, Sorry this is a bit of a noob question. I have the following select statement. I would like to update the values of ContactAssociate from 'Bob' to 'Jane'. Is it possible to do this?

SELECT TOP (1500) ContactID, ContactNotes, ContactAssociate, ContactAppointment
FROM  tb_Contact
WHERE (ContactAssociate = 'Bob') AND (ContactAppointment = 0)

Any help appreciated.

+1  A: 
UPDATE tb_Contact SET ContactAssociate='Jane'
 WHERE ContactID IN
      (
           SELECT TOP (1500) ContactID
           FROM  tb_Contact
           WHERE (ContactAssociate = 'Bob') AND (ContactAppointment = 0)
      )
  • For general tutorial on UPDATE see here.
  • For a specific reference for MSSQL see here.
Am
Thanks, that will update all the records in the table though. I only want to update 1500 where the ContactAppointment column = 0.
Chin
ah, the question wasn't clear enough
Am
modified to your request
Am
@Am: Better to link to vendor documentation - vendor agnostic is liable to miss details.
OMG Ponies
@Am: It's redundant to check for the associate name if it's already done in the subquery that will return primary keys.
OMG Ponies
Agreed, though if the OP is new, a "light" tutorial might be friendlier.
Am
+1: I admit, I don't care for the MS documentation format.
OMG Ponies
@Ponies: tnx, Fixed. I wonder if the query compiler would have fixed it anyways.
Am
Missing the `WHERE` :) Maybe, but I'd take any chance to use a primary key whenever I can.
OMG Ponies
+4  A: 

Use:

UPDATE TB_CONTACT
   SET contactassociate = 'Jane'
 WHERE contactassociate = 'Bob'

The query you supplied checked for contactappointment being zero - if you wanted to include that check, the query would be:

UPDATE TB_CONTACT
   SET contactassociate = 'Jane'
 WHERE contactassociate = 'Bob'
   AND contactappointment = 0

The UPDATE statement doesn't support the TOP keyword, so your update statement would be:

UPDATE TB_CONTACT
   SET contactassociate = 'Jane'
 WHERE contactid IN (SELECT TOP (1500)
                            contactid 
                       FROM TB_CONTACT
                      WHERE contactassociate = 'Bob'
                        AND contactappointment = 0)

...but that will give random contacts - you should specify an ORDER BY clause in the subquery to get consistent results.

Reference:

OMG Ponies
Thanks, as I said - that will update all the records in the table though. I only want to update 1500 where the ContactAppointment column = 0.
Chin