I don't like cursors much but I cold not find other solution. I might try later doing this without cursors.
/* Sample data.*/
create TABLE #LandParcel (BlockID INT, ParcelNo INT, NameofOnwe VARCHAR(50))
insert INTo #LandParcel select 11001 , 1056 , 'Chandana'
insert INTo #LandParcel select 11001 , 1078 , 'Sisil'
insert INTo #LandParcel select 11001 , 1158 , 'Kumara'
insert INTo #LandParcel select 11078 , 105 , 'SK'
insert INTo #LandParcel select 11078 , 245 , 'Shantha'
CREATE TABLE #Actions (Blockid INT, ParcelNo INT, ActionTaken VARCHAR(50))
insert INTo #Actions select 11001 , 1056 ,'Received'
insert INTo #Actions select 11001 , 1078 , 'Received'
insert INTo #Actions select 11001 , 1158 , 'Received'
insert INTo #Actions select 11078 , 105 , 'Received'
insert INTo #Actions select 11078 , 245 , 'Received'
insert INTo #Actions select 11001 , 1056 , 'Send To LR'
insert INTo #Actions select 11001 , 1078 , 'Send to LR'
insert INTo #Actions select 11078 , 105 , 'Send To LT'
/* End sample data */
/* Update query*/
CREATE TABLE #temp (BlockId INT, ActionTaken VARCHAR(50), ParcelNumbers VARCHAR(100))
INSERT INTO #temp
SELECT l.blockid, a.ActionTaken, NULL
FROM #LandParcel l INNER JOIN #Actions a on l.blockid = a.blockid
GROUP BY l.blockid, a.actiontaken
DECLARE @blockId INT
DECLARE @actionTaken VARCHAR(50)
DECLARE @parcel VARCHAR(100)
SET @parcel = ''
DECLARE @cursorParcel CURSOR
SET @cursorParcel = CURSOR FAST_FORWARD
FOR
SELECT blockid, ActionTaken FROM #temp
OPEN @cursorParcel
FETCH NEXT FROM @cursorParcel
INTO @blockId,
@actionTaken
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @parcel = CASE @parcel
WHEN '' THEN convert(VARCHAR(10), a.ParcelNo )
ELSE @parcel + ', ' + convert(VARCHAR(10), a.ParcelNo )
END
from #temp t INNER JOIN #Actions a on t.blockid = a.blockid and t.actiontaken = a.actiontaken
where t.BlockId = @blockId
AND t.ActionTaken = @actionTaken
UPDATE #temp SET ParcelNumbers = @parcel
WHERE BlockId = @blockId
AND ActionTaken = @actionTaken
SET @blockId = NULL
SET @actionTaken = NULL
SET @parcel = ''
FETCH NEXT FROM @cursorParcel
INTO @blockId,
@actionTaken
END
CLOSE @cursorParcel
DEALLOCATE @cursorParcel
SELECT * FROM #temp
DROP TABLE #temp
DROP TABLE #LandParcel
DROP TABLE #Actions