Skip to content
Advertisement

Return multiple tables specific to each column

I would like to get a more simple query that runs through all columns of a table and returns the SAME number of tables for EACH column.

For example…

would return four tables if ran at once. This gives the results I would like but I would have to type out each column, being especially pesky if I had many many columns. How can I write a query that would go through all the columns and give me the same results without having to do this?

Advertisement

Answer

Based on our conversation in the comments, you are happy to use dynamic TSQL and you have permissions to execute it on your server.

Therefore, one way to achieve this is to enumerate the columns using a cursor and then execute some dynamic TSQL to get the result set for each column.

The following example shows how it can be done. Simply modify @table to be the name of whichever table you want and it will output every column as a single result set:

In this case, the CURSOR enumerates all of the columns that belong to your table.

You then iterate through these, storing the column name (from COLUMN_NAME in a variable @column), build a piece of dynamic SQL (is @s) and then execute it.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement