1

I have a table but i don't know its columns. It name is X

I can find its columns with the following code:

DECLARE @columnNames NVARCHAR(4000) = ''
SELECT @columnNames = @columnNames + ', ' + COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = 'X'

Now, i want to use select statement in my table, but how?

I think, it should be like that. I didn't find correct way:

SELECT SUBSTRING(@columnNames, 2, LEN(@columnNames)) FROM X

edit:

Actually i want to merge columns without id column.

DECLARE @columnNames NVARCHAR(4000) = ''
SELECT @columnNames = @columnNames + ' + ' + COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = 'X' AND COLUMN_NAME <> 'id'

And then

SELECT SUBSTRING(@columnNames, 4, LEN(@columnNames)) FROM X
2
  • 4
    I know it's bad form, but why doesn't select * from X work for you? Commented Jan 4, 2011 at 15:36
  • actually i want to merge columns without id column. SELECT @columnNames = @columnNames + ' + ' + COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = 'X' AND COLUMN_NAME <> 'id' and then i want to use select... Commented Jan 4, 2011 at 15:39

4 Answers 4

2

Following the clarified goal and explanation as to why * won't work for you, you would need to concatenate the entire SELECT statement and use dynamic SQL. You should use QUOTE_NAME to avoid problems with non standard names.

See The Curse and Blessings of Dynamic SQL: Dealing with Dynamic Table and Column Names

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

Comments

2

If you are selecting all of the columns of your table, why don't just use SELECT * FROM X?. The other way is with dynamic sql and thats not a good idea.

1 Comment

because of merge columns... thanx for your answer.
1

If you want to select the fields in the string you fetch you would need to use EXEC (or sp_executesql)

DECLARE @columnNames NVARCHAR(4000) = ''
SELECT @columnNames = @columnNames + case when len(@columnNames)=0 then '' else ', ' end + COLUMN_NAME FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = X

DECLARE @SQL NVARCHAR(1024) = 'select ' + @columnNames + ' from X'
EXEC (@SQL)

Comments

1

you need to use dynamic SQL to do that, but be aware of the dangers, read this http://www.sommarskog.se/dynamic_sql.html

But since you are selecting all columns I don't see the point in what you are doing...just use SELECT * FROM X

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.