I have two tables as below and am using SQL server
Table1
+-----------------------------------+
| Codes |
+-----------------------------------+
| KNC-BAI-PFB-BRAND-ZONE-ADS |
| KNC-BAI-PFB-CHUCHUANG-BRAND-LINK2 |
| KNC-BAI-PFB-FIXED-PACK1-logo |
| KNC-GAT-GEN-KWL-CATCHALL |
| KNC-GAT-GEN-KWL-CATCHALL |
| KNC-GAT-GEN-KWL-CATCHALL |
| KNC-XRU-GEN-PFB-Farnell_Exact |
| KNC-MUK-PFB-FARNELL-exact |
| KNC-MUK-GEN-SKU-TOP1000 |
+-----------------------------------+
Table2
+-----------------+--------------------------+
| Level0 | Level1 |
+-----------------+--------------------------+
| KNC-BAI-PFB | KNC-BAI-PFB-BRAND-ZONE |
| KNC-BAI-PFB | KNC-BAI-PFB-FIXED |
| KNC-GAT-GEN-KWL | KNC-GAT-GEN-KWL-CATCHALL |
| KNC-XRU-GEN | KNC-XRU-GEN-PFB |
| KNC-MUK-PFB | |
| KNC-MUK-GEN-SKU | |
+-----------------+--------------------------+
In table2, the values in level1 have additional string added to the level0. If there is no additional string values in level0, they are blank.
I would want to get a new column with the data from table1 based on the condition using table2.
I am trying to get output something like this.
if(table1.codes contains table2.level1) give me value from table2.level1 else give me the value from table2.level0 as "newcode"
I would want to get the output as below, where if there is a value found in level1 that value is returned and then if there is not match in level1, match it with level0 and return level0 value against the code. it shouldn't match both the values in table2, without duplication of the codes.
+-----------------------------------+--------------------------+
| Codes | Newcodes |
+-----------------------------------+--------------------------+
| KNC-BAI-PFB-BRAND-ZONE-ADS | KNC-BAI-PFB-BRAND-ZONE |
| KNC-BAI-PFB-CHUCHUANG-BRAND-LINK2 | KNC-BAI-PFB |
| KNC-BAI-PFB-FIXED-PACK1-logo | KNC-BAI-PFB-FIXED |
| KNC-GAT-GEN-KWL-CATCHALL | KNC-GAT-GEN-KWL-CATCHALL |
| KNC-GAT-GEN-KWL-CATCHALL | KNC-GAT-GEN-KWL-CATCHALL |
| KNC-GAT-GEN-KWL-CATCHALL | KNC-GAT-GEN-KWL-CATCHALL |
| KNC-XRU-GEN-PFB-Farnell_Exact | KNC-XRU-GEN-PFB |
| KNC-MUK-PFB-FARNELL-exact | KNC-MUK-PFB |
| KNC-MUK-GEN-SKU-TOP1000 | KNC-MUK-GEN-SKU |
+-----------------------------------+--------------------------+