I need to generate common backup codes based on the available backup products across the table. Below is the backup product table
if object_id('tempdb..#pdt') is not null
DROP TABLE #pdt
create table #pdt(ROW_NUM INT IDENTITY(1,1), PRODUCT NVARCHAR(30), PDT_CODE
NVARCHAR(10),BKP_PRODUCT NVARCHAR(30),BKP_PDT_CODE NVARCHAR(10))
INSERT #pdt( PRODUCT,PDT_CODE, BKP_PRODUCT,BKP_PDT_CODE )
VALUES ('HP','HP','DELL SERIES','DS'),('HP', 'HP','LENOVO NEW','LN'),
('DELL SERIES','DS','LENOVO NEW','LN'),
('DELL SERIES','DS','DELL SERIES GEN1','DG'),
('DELL SERIES','DS','DELL SERIES GEN1 NEW','DN'),
('SONY','SO','TOSHIBA','TO'),
('SONY','DS','ACER','AC')
INSERT #pdt(PRODUCT,PDT_CODE, BKP_PRODUCT,BKP_PDT_CODE )
VALUES ('APPLE','AP','APPLE','AP')
INSERT #pdt(PRODUCT,PDT_CODE, BKP_PRODUCT,BKP_PDT_CODE )
VALUES ('ACER','AC','APPLE','AP')
SELECT * FROM #pdt
ROW_NUM PRODUCT PDT_CODE BKP_PRODUCT BKP_PDT_CODE
----------- ------------------------------ ---------- ---------------------
--------- ------------
1 HP HP DELL SERIES DS
2 HP HP LENOVO NEW LN
3 DELL SERIES DS LENOVO NEW LN
4 DELL SERIES DS DELL SERIES GEN1 DG
5 DELL SERIES DS DELL SERIES GEN1 NEW DN
6 SONY SO TOSHIBA TO
7 SONY DS ACER AC
8 APPLE AP APPLE AP
9 ACER AC APPLE AP
Here the backup relationship is bidirectional. HP is a backup to DELL SERIES and vice versa. we need to create a common backup code for each product. This backup code is created by considering all backup combinations(recursions). The backup code is a concatenation of the pdt_code of all the backups.Below is the logic: For HP the backup is DELL SERIES. But DELLSERIES has got LENOVO NEW ,DELL SERIES GEN1,DELL SERIES GEN1 NEW as backups. So the backup code for HP is: HP+DS+LN+DG+DN = HPDSLNDGDN
For DELL SERIES the backup is LENOVO NEW(Row 3). But from Row 4,5 we also have backups DELL SERIES GEN1,DELL SERIES GEN1 NEW. Also DELL SERIES itself is a backup of HP(Row 1) So the backup code for DELL SERIES is same as above(as all are involved, order doesnt matter) = HPDSLNDGDN
similarly we need to generate the backup_code for all other products dynamically. Backup code order of concatenation of codes doesnt matter.
Note: For Apple the backup code wil be just AP ad as both product and bkp_product are same. I am using SQL Server 2012.
`` Below is the expect result:
ROW_NUM PRODUCT PDT_CODE BKP_PRODUCT BKP_PDT_CODE BACKUP_CODE
----------- ------------------------------ ---------- ----------------------
1 HP HP DELL SERIES DS HPDSLNDGDN
2 HP HP LENOVO NEW LN HPDSLNDGDN
3 DELL SERIES DS LENOVO NEW LN HPDSLNDGDN
4 DELL SERIES DS DELL SERIES GEN1 DG HPDSLNDGDN
5 DELL SERIES DS DELL SERIES GEN1 NEW DN HPDSLNDGDN
6 SONY SO TOSHIBA TO SOTOACAP
7 SONY DS ACER AC SOTOACAP
8 APPLE AP APPLE AP AP
9 ACER AC APPLE AP ACAPSOTO
Please help me in generating the code dynamically.
Thanks very much.