I have 2 tables as below. The first table holds the order of the SQL columns I want to output. The second table has the transaction data with matching column names to the first table. Note: All the column names in the second table is a data row in the first table and matched to the "TableColumnName" field. Client can change the output order of the columns from zGenericOrder table.
E.g. Country is the first column I want to output from the zAddress table as it is the column I want to output first (this is kept in zGenericOrder table)
Pretty much my final output required, based on this example is something like below. This requires to do dynamically.
SELECT Country,FirstName,LastName,Suburb,Address1,Address2 FROM dbo.zAddress
Is this achievable using SQL only?
1条答案
按热度按时间qlckcl4x1#
This is just a simple dynamic sql exercise:
To get a list of columns i use STRING_AGG which creates a CSV list of columns in form of: Col1,Col2,Col3.
WITHIN GROUP (ORDER BY OrderBy)
ensures correct order.Then you just execute the select by concatenating your column list.