-1

I have 2 SQL Server tables that both have hundreds of columns.

A sample of table 1 is:

ID    ColA   ColC   ColD  ColF ...

A sample of table 2 is:

ID    ColB   ColE ...   

I need to join on column ID but then have the columns print out alphabetical. For right now I need the names of the columns in alphabetical order. I don't care about the data in each column yet.

So it should be:

ID  ColA  ColB  ColC  ColD  ColE  ColF ...
1
  • 1
    That doesn't matter and isn't your call
    – cdub
    Sep 24, 2013 at 21:12

1 Answer 1

1

You can use this to help build the query:

SELECT ',' + name 
FROM sys.columns
WHERE object_id IN (OBJECT_ID('Table1'),OBJECT_ID('Table2'))
ORDER BY name

Update: Dynamic SQL version (still have to plop table names in manually):

DECLARE @sql VARCHAR(MAX)
       ,@cols VARCHAR(MAX)
SET @cols = (SELECT STUFF((SELECT ',' + Name
                           FROM (SELECT DISTINCT Name
                                  FROM sys.columns
                                  WHERE object_id IN (OBJECT_ID('Table1'),OBJECT_ID('Table2'))
                                     AND Name <> 'ID'
                                  )sub
                            ORDER BY name
                            FOR XML PATH('')        
                            ), 1, 1, '' ))
SET @sql = 'SELECT ' +@cols+'
            FROM Table1 a
            JOIN Table2 b
              ON a.ID = b.ID
           '
EXEC (@sql)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.