Question

I want to update GroupID column of massemail_emailmaster and set it to the value as it is stored on massemail_groupmaster. Both table has GroupName column which is I have used to join in the subquery. But the following query is giving me error. Error message is incorrect syntax near a3. I don't understand the mistake in syntax here. Please help.

UPDATE [dbo].[massmail_emailmaster]  a3
set a3.GroupId =
      (select TOP 1 a1.GroupID from [dbo].[massmail_groupmaster] a1 
         join [dbo].[massmail_emailmaster] a2
      on a1.[groupname] = a2.[groupname]
where a3.[GroupName]=a2.[GroupName]) 

DDL of table [dbo]. [massmail_emailmaster]

(ClientID, varchar(50)),
           (uid, int)
           (Name, varchar(100))
           (GroupName, varchar(100))
           (Email, varchar(100))
           GroupId, int)

DDL of table

[dbo]. [massmail_groupmaster]
 (Clientid, varchar(50))
           ,(uid, int)
           ,(groupname, varchar(100))
(GroupId,int))
Was it helpful?

Solution

You can use the alias in the update when you later define it in the from clause. (This is a "perverse" situation where the alias is defined after its first use.)

UPDATE a3
    set GroupId = (select TOP 1 a1.GroupID
                   from [dbo].[massmail_groupmaster] a1
                   where a1.[groupname] = a3.[groupname]
                  )
    FROM [dbo].[massmail_emailmaster] a3;

OTHER TIPS

UPDATE  a2
SET a2.GroupId = (SELECT TOP 1 a.GroupID 
                   FROM [dbo].[massmail_groupmaster] a 
                   INNER JOIN [dbo].[massmail_emailmaster] b
                   ON a.[groupname] = b.[groupname]
                  ) 
FROM  [dbo].[massmail_emailmaster] a2
WHERE a.[groupname] = a2.[groupname]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top