Monday, March 26, 2012

How to Index through a tables Columns

I am trying to index through the columns of MyTable so I can do the same work on all columns. I know how to get the column names from MyTable but when I use @.MyColName in the SELECT statement to get MyTable Column 0 Row values I get a table with the column name in each row cell. I can't get the syntax correct to return the value in each cell for that column.

This is a extremely simplified example !!!!!!
DECLARE @.MyColName nvarchar(30)

--Get the MyTable Column 0 Name
SELECT @.MyColName = Col_Name(Object_ID('MyTable'), 0)

--Display the MyTable Column 0 Row values
SELECT @.MyColName FROM MyTable --This is the syntax I can not get correct

Can anyone help ?

Thanks

You can't use a variable for a column name; you will have to usedynamic SQL to meet your goal. Build the SQL statement in avariable and then EXECUTE it, like this:
DECLARE @.MySQLStatement varchar(500)
SELECT @.MySQLStatement = 'SELECT ' + @.MyColName + ' FROM MyTable'
EXECUTE(@.MySQLStatement)


|||

tmorton

Thanks for your responce, I will give it a try.

No comments:

Post a Comment