I have 3 tables:
Accounts (fields used: ID varchar(20) and Name varchar(50))
OpttyPartner( fields used : ID15 varchar(20) , ACCOUNTTOID varchar(20)
Final2([Opportunity ID] varchar(20), Partner varchar(400)
I need to update Partner field of every record for final2 with name from accounts table. Final2 is related to OpptyPartner with {opportunity ID] and ID15 Accounts is related with OpptyPartner with ID and ACCOUNTTOID
If there are more than one accounttoid for same Opportunity ID then the names should be appended and seperated with a ';'
For example:
Final2
ID Partner
1
OpptyPartner
ID15 ACCOUNTTOID
1 A1
1 A2
Accounts
ID Name
A1 ABC com
A2 EFG com
The output in Partner should be 'ABC com;EFG com'
How can this be achieved? Cursors ?
UPDATE:
;With partners as
(select * from Accounts inner 开发者_JAVA技巧join OpptyPartner on
Accounts.ID COLLATE Latin1_General_CS_AS=OpptyPartner.[ACCOUNTTOID] COLLATE Latin1_General_CS_AS
inner join Final2 on Final2.[Opportunity ID] = OpptyPartner.ID15)
Update Final2 set Partner = p.Names from
Final2 inner join
(select [Opportunity ID] , LEFT(Names, len(Names)-1) as Names from
(SELECT j.[Opportunity ID] ,
( SELECT cast(p1.NAME as varchar(10)) + ';'
FROM partners p1
WHERE p1.[Opportunity ID] = j.[Opportunity ID]
ORDER BY NAME
FOR XML PATH('') ) AS Names
FROM partners j
GROUP BY [Opportunity ID] )A
) p on Final2.[Opportunity ID] = p.[Opportunity ID]
I think this might be of use:
;With partners as
(select [Opportunity ID], Name from accounts inner join OpttyPartner on
accounts.id=OpttyPartner.[ACCOUNTTOID]
inner join final2 on final2.[Opportunity ID] = OpttyPartner.id15)
Update final2 set partner = p.names from
final2 inner join
(select [Opportunity ID] , LEFT(Names, len(Names)-1) as Names from
(SELECT j.[Opportunity ID] ,
( SELECT cast(p1.Name as varchar(10)) + ';'
FROM partners p1
WHERE p1.[Opportunity ID] = j.[Opportunity ID]
ORDER BY Name
FOR XML PATH('') ) AS Names
FROM partners j
GROUP BY [Opportunity ID] )A
) p on final2.[Opportunity ID] = p.[Opportunity ID]
Try using this (add collation where necessary) if you have multiple records in opptyPartner with same ID15 and ACCOUNTTOID :
;With partners as
(select [Opportunity ID], Name from accounts inner join (select distinct [ID15]
,[ACCOUNTTOID] from OpttyPartner) OpttyPartner on
accounts.id=OpttyPartner.[ACCOUNTTOID]
inner join final2 on final2.[Opportunity ID] = OpttyPartner.id15)
Update final2 set partner = p.names from
final2 inner join
(select [Opportunity ID] , LEFT(Names, len(Names)-1) as Names from
(SELECT j.[Opportunity ID] ,
( SELECT cast(p1.Name as varchar(10)) + ';'
FROM partners p1
WHERE p1.[Opportunity ID] = j.[Opportunity ID]
ORDER BY Name
FOR XML PATH('') ) AS Names
FROM partners j
GROUP BY [Opportunity ID] )A
) p on final2.[Opportunity ID] = p.[Opportunity ID]
精彩评论