Click here to Skip to main content
15,884,883 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. I have 2 tables with some data with same value. Now i want to update one column of one table using join with another. But i need a single value to be updated in each row instead of comma separated.

I am giving the example here with what i have tried.

What I have tried:

create table #tmp1(id int,pnum varchar(100),amount numeric(18,2),RecNo varchar(100))
create table #tmp2(id int,pnum varchar(100),amount numeric(18,2),RecNo varchar(100))


insert into #tmp1 values(1,'P1',100,'Rec1')
insert into #tmp1 values(2,'P2',100,'Rec2')
insert into #tmp1 values(3,'P1',100,'Rec3')
insert into #tmp1 values(4,'P1',100,'Rec4')
insert into #tmp1 values(5,'P3',100,'Rec5')

insert into #tmp2(id,pnum,amount) values(1,'P1',100)
insert into #tmp2(id,pnum,amount) values(2,'P1',100)
insert into #tmp2(id,pnum,amount) values(3,'P1',100)
insert into #tmp2(id,pnum,amount) values(4,'P3',100)

UPDATE  a
SET     a.RecNo = b.ReceiptList
FROM    #tmp2 a
		INNER JOIN
		(
			SELECT  pnum,
					STUFF((SELECT ',' + RecNo
							FROM #tmp1
							WHERE pnum = a.pnum and amount=a.amount
							FOR XML PATH ('')), 1, 1, '')  AS ReceiptList
			FROM    #tmp2 AS a
			GROUP   BY pnum,amount
		) b ON a.pnum = b.pnum
WHERE   b.ReceiptList IS NOT NULL

select * from #tmp2
		
drop table #tmp1
drop table #tmp2


I am getting the output like this:


id	pnum	amount	RecNo
1	P1	100.00	Rec1,Rec3,Rec4
2	P1	100.00	Rec1,Rec3,Rec4
3	P1	100.00	Rec1,Rec3,Rec4
4	P3	100.00	Rec5

however i want the output like below:

id	pnum	amount	RecNo
1	P1	100.00	Rec1
2	P1	100.00	Rec3
3	P1	100.00	Rec4
4	P3	100.00	Rec5
Posted
Updated 18-Dec-19 1:01am

Seems, you need simplest version of UPDATE statement:

SQL
DECLARE @tmp1 TABLE(id int,pnum varchar(100),amount numeric(18,2),RecNo varchar(100))
DECLARE @tmp2 TABLE(id int,pnum varchar(100),amount numeric(18,2),RecNo varchar(100))

INSERT INTO @tmp1(id, pnum, amount, RecNo)
VALUES(1,'P1',100,'Rec1'), (2,'P2',100,'Rec2'), (3,'P1',100,'Rec3'),
(4,'P1',100,'Rec4'), (5,'P3',100,'Rec5')

INSERT INTO @tmp2(id,pnum,amount) 
VALUES(1,'P1',100), (2,'P1',100), (3,'P1',100), (4,'P3',100)

UPDATE a
SET a.RecNo = b.RecNo
FROM @tmp2 a INNER JOIN @tmp1 b ON a.pnum = b.pnum

SELECT *
FROM @tmp2 


Result:
id	pnum	amount	RecNo
1	P1	100.00	Rec1
2	P1	100.00	Rec1
3	P1	100.00	Rec1
4	P3	100.00	Rec5
 
Share this answer
 
The reason you're getting a comma-delimited list of values is because of the subquery in your join. This code is what's doing it.

SQL
STUFF((SELECT ',' + RecNo
FROM #tmp1
WHERE pnum = a.pnum and amount=a.amount
FOR XML PATH ('')), 1, 1, '')  AS ReceiptList
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900