简体   繁体   English

传递选择查询的列名以从临时表中检索

[英]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). 我有一个临时表,其中包含要从特定表(表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 这里的表A包含10列以上

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? 为什么在地球上,您需要将列名存储在表变量中,以后再读取它以构建sql语句?

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 这应该让你走

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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