Sql-server – Select using values from another table

sql server

I want to select specific columns from a table, let's say table A. Table B has the names of the names of the columns I would like to select. How would I write a MSSQL query that will use the distinct values from Table B as the column names that I want to query from table A?

Best Answer

Can't you just use the COALESCE function like this?

DECLARE @columnList VARCHAR(MAX), @sql VARCHAR(MAX)
SELECT @columnList = COALESCE(@columnList+',' ,'') + columnName
FROM TableB

SET @sql = 'SELECT ' + @columnList + ' FROM TableA'

EXEC(@sql)