开发者

update SQL Query using 3 tables

开发者 https://www.devze.com 2023-02-15 06:14 出处:网络
I have 3 tables Table A Account IdAccount Name 1Account1 2Account2 3Account3 Table B Opp IDPartner Account ID

I have 3 tables

Table A
Account Id         Account Name
1                  Account1
2                  Account2
3                  Account3

Table B

  Opp ID            Partner Account ID
  O11               1
  O11               2

Table C

  Opp Id           Pstring
  O11
  O12

I want to update Table C Pstring with account name, if there 2 account ids for same oppID then they should be appended with a semicolon between them and updated in Pstring

For example

  • For Opp Id O11, Pstring should have Account1;Account2

How can I achiev开发者_开发问答e this? Any pointer would be of great help.


Sample tables

create table A (AccountId int, AccountName varchar(100))
insert A select 1 ,'Account1'
insert A select 2 ,'Account2'
insert A select 3 ,'Account3'
create table B (OppID varchar(10), PartnerAccountID int)
insert B select 'O11', 1
insert B select 'O11', 2
create table C (OppId varchar(10), Pstring varchar(1000))
insert C (OppId) select 'O11'
insert C (OppId) select 'O12'

Create a function to concat account names for an OppID (one-off creation)

create function dbo.concatAccountName(@OppId varchar(10)) returns varchar(8000)
as
begin
declare @tmp varchar(8000)
select @tmp = isnull(@tmp+';','') + A.AccountName
from A
inner join B on A.AccountID = B.PartnerAccountID
where B.OppID=@OppId and A.AccountName is not null
return @tmp
end
GO

The update query

update C
set PString = dbo.concatAccountName(OppID)


Try something like this:

UPDATE C
SET PString = X.PString
FROM
 (
   SELECT OppID, 
       (SELECT CAST(AccountName + ';' AS VARCHAR(MAX)) 
        FROM A 
        WHERE (A.AccountID = B.PartnerAccountID) 
        FOR XML PATH ('')
      ) AS PString
   FROM B
  ) X
WHERE X.OppID = C.OppID

See also this question for more detials.

0

精彩评论

暂无评论...
验证码 换一张
取 消