I have a Customer table :
| CustomerID | FirstName | LastName |
|---|---|---|
| 1 | Ben | Brown |
| 2 | Adam | Green |
And I would like to order it based on another table TableInfo which contains the column names of the first table in rows and the order direction.
| Source_Table | Source_Column | Order_By | Order_Of_Order_By |
|---|---|---|---|
| Customer | CustomerID | NULL | NULL |
| Customer | FirstName | ASC | 1 |
| Customer | LastName | NULL | NULL |
The first table can be anything, the second table will always contain the same column headers, but the rows will depend on the first table.
I would like to do something like
select * from Customer
order by
(select Source_Column + ' '+ Order_By from TableInfo where order_by is not NULL)
This doesn't work as I can't use this subquery as an Order by column name.
How can I make it work?