1

I've cooked up the following SQL to generate the select portion of a query that, given a table, lists all columns in said table:

declare @cols nvarchar(max);
set @cols = '';

SELECT @cols += lower(', ' + c.name)
FROM sys.columns c
WHERE c.object_id = OBJECT_ID('tablename')

select RIGHT(@cols, LEN(@cols) - 2);

-- output:
-- id, sex, isactive, displayname ...

Is there a better way to do this? Are there any tools that can perform this task quickly?

I'm trying to prevent having to write out a bunch of column names. Would much rather generate a list, as described in the code snippet, and remove columns I'm not going to need.

1
  • 1
    In SSMS, You can also right click on table and choose: Script Table As - Select to - New query editor window Commented Feb 19, 2014 at 5:09

3 Answers 3

4

In SQL Server Management Studio you can drag and drop the Columns folder into any Query window which gives you those same results quickly (though not programmatically of course).

enter image description here

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

+1 that's cool, but i don't like mice and the click-n-drag bit. looking for a more intelligent method. maybe a third-party tool, macro, or some other amalgamation.
3

Another way

select stuff((SELECT  lower(' ,' + c.name)
FROM sys.columns c
WHERE c.object_id = OBJECT_ID('<<TABLENAME>>')
for xml path('')),1,2,'')

Comments

0
select
@cols =stuff((SELECT  ', ' + c1.name FROM sys.columns c1 where c.object_id=c1.object_id for xml path('')),1,1,'')
FROM sys.columns c
WHERE c.object_id = OBJECT_ID('tablename')

select @cols

Comments

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.