简体   繁体   中英

Pass Column names for a Select Query to retrieve from temporary table

I had a temporary table that contains the column names that I want to retrieve from the specific table (table A).

Here's the sample code:

Declare @temp table (ColumnNames varchar(30))

insert into @temp 
values('Name'), ('Class'), ('School')

--select Query to retrieve only name,class and School columns
end

Here table A contains more than 10 columns

The following code does what you asked for:

Declare @temp table (ColumnNames varchar(30))

insert into @temp 
values('Id'), ('Name')

DECLARE @ColumnNames nvarchar(max)

SELECT @ColumnNames = stuff((SELECT ',' + ColumnNames 
FROM @temp
FOR XML PATH('')), 1,1, '')

EXEC (N'SELECT ' + @ColumnNames + N' FROM TheTable')

But something is fundamentally wrong with this. Why on Earth you need to store column names in a table variable and later read it to build the sql statement?

DECLARE @SQLTOEXECUTE VARCHAR(MAX),
           @Col VARCHAR(200)

DECLARE CURSOR curs FOR 
SELECT ColumnNames FROM @temp

SET @SQLTOEXECUTE = 'SELECT '

OPEN curs
FETCH NEXT FROM Curs
INTO @Col

WHILE @@FETCH_STATUS = 0 
BEGIN
   SET @SQLTOEXECUTE = @SQLTOEXECUTE + @Col + ', '

   FETCH NEXT FROM Curs
   INTO @Col
END

CLOSE curs
DEALLOCATE curs

SET @SQLTOEXECUTE = ' FROM <Table name goes here>' 
PRINT @SQLTOEXECUTE

This should get you going

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM