传递 Select 查询的列名以从临时 table 中检索
Pass Column names for a Select Query to retrieve from temporary table
我有一个临时 table,其中包含我想从特定 table (table A) 中检索的列名。
示例代码如下:
Declare @temp table (ColumnNames varchar(30))
insert into @temp
values('Name'), ('Class'), ('School')
--select Query to retrieve only name,class and School columns
end
此处tableA包含超过10列
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
这应该会让你继续前进
以下代码可以满足您的要求:
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')
但这从根本上是错误的。为什么你需要将列名存储在 table 变量中,然后读取它来构建 sql 语句?
我有一个临时 table,其中包含我想从特定 table (table A) 中检索的列名。
示例代码如下:
Declare @temp table (ColumnNames varchar(30))
insert into @temp
values('Name'), ('Class'), ('School')
--select Query to retrieve only name,class and School columns
end
此处tableA包含超过10列
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
这应该会让你继续前进
以下代码可以满足您的要求:
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')
但这从根本上是错误的。为什么你需要将列名存储在 table 变量中,然后读取它来构建 sql 语句?