0

I have 2 tables, one containing IDs and data attributes and another containing Attribute descriptions.

What I need to do is to read the ID and all Attribute columns (needs to be dynamic, as they could add more attributes later) but with the descriptions from Table2 as the column headers. (NB: The attributes do not have similar names, so I can't just read where column name starts with 'Attr' or anything).

Table 1:

ID     ID_Description     Col1     aAttr1    xAttr2    yAttr3    zAttr4
1      First Thing        Blah     103       Gtr       A1        
2      Second Thing       Blah     52        Hte       B2        U123
3      Third Thing        Blah     17        xxx       xx        xxx

Table 2

Attr_ID     Attr_Desc
aAttr1      Site
xAttr2      Area
yAttr3      Rack
zAttr4      Shelf

So I need to pull ID plus all columns from Table 1 that have an entry in the Attr_ID column of Table 2, and replace the column headers for those Attr columns with the Attr_Desc entry from Table 2:

ID     Site     Area     Rack     Shelf
1      103      Gtr      A1       
2      52       Hte      B2       U123
3      17       xxx      xx       xxx

Any pointers would be gratefully received. Thanks for looking.

** Edit ** I know that I can use an INFORMATION_SCHEMA.COLUMNS lookup to get the column names, but I don't know how to (or even whether I can) incorporate that into the overall SELECT statement and to then replace the column names with the descriptions from table 2:

SELECT [Column_Name] FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = N'Table1' 
and Column_Name in (select Attr_ID from [dbo].[Table2])
2
  • Your database design may need to change, because you can't really directly do this without using dynamic SQL, which means writing code to generate SQL code. Commented Nov 24, 2021 at 16:03
  • Problem is, the design is fixed as it's an existing database. So I just need to try to find a way to do it. Commented Nov 24, 2021 at 16:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.