Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

select certain columns

Status
Not open for further replies.

ter79

IS-IT--Management
Jul 11, 2001
106
US
I have two tables that I need to use to create a specific select statement.

One table (AllData) contains approx 45 columns and data in each column. The other table (ColumnList) holds the names of the columns and a flag.

What I need to do is create a select statement against AllData that will only use the columns indicated in ColumnList

Example
AllData table

ColumnNames:
FirstName
LastName
DOB
Gender
State
Zip


ColumnList Table
ColumnName Use
FirstName True
LastName True
DOB False
Gender True


Therefore my select statement would be something like

select FirstName, LastName from AllData

since the "Use" flag can change I need to make this dynamic

Hope this makes sense
 
I forgot to add this part... I still need to return the PK from each row, even though that field is not defined in the ColumnList table
 
Code:
DECLARE @sql nvarchar(max)-- change it 4000 if you use SQL 2000

SET @sql = N'SELECT PrimaryKey'
SELECT @sql = @sql + ','+ColumnName
FROM ColumnList
WHERE [Use] = 1 -- bit field, isn't it?

SET @sql = @sql + N' FROM AllData'
EXEC sp_executesql @sql
NOT TESTED!

Borislav Borissov
VFP9 SP2, SQL Server 2000/2005.
 
Thanks... Worked perfectly!!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top