如何将结果集中的列用作SELECT中FROM子句的参数

时间:2016-07-04 08:27:28

标签: sql sql-server sql-server-2012

我的结果集存储在像这样的变量

DECLARE @tmpTable TABLE([table] sysname, [column] sysname);
INSERT INTO @tmpTable
    SELECT tab1.name AS [table],
        col1.name AS [column] 
    FROM sys.foreign_key_columns fkc
     INNER JOIN sys.objects obj
      ON obj.object_id = fkc.constraint_object_id
     INNER JOIN sys.tables tab1
      ON tab1.object_id = fkc.parent_object_id
     INNER JOIN sys.schemas sch
      ON tab1.schema_id = sch.schema_id
     INNER JOIN sys.columns col1
      ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
     INNER JOIN sys.tables tab2
      ON tab2.object_id = fkc.referenced_object_id
     INNER JOIN sys.columns col2
      ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id
WHERE tab2.name = 'sometable'

这给了我一个这样的结果集:

| table | column |
|-------|--------|
| tab1  | col4   |
| tab2  | col12  |
| tab2  | col1   |

我现在需要的是从上面的结果集中查询每个表格并获取列“#”列的值。从那张桌子。

2 个答案:

答案 0 :(得分:0)

您需要使用动态SQL

create TABLE tmpTable ([table] sysname, [column] sysname);
INSERT INTO tmpTable
    SELECT tab1.name AS [table],
        col1.name AS [column] 
    FROM sys.foreign_key_columns fkc
     INNER JOIN sys.objects obj
      ON obj.object_id = fkc.constraint_object_id
     INNER JOIN sys.tables tab1
      ON tab1.object_id = fkc.parent_object_id
     INNER JOIN sys.schemas sch
      ON tab1.schema_id = sch.schema_id
     INNER JOIN sys.columns col1
      ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
     INNER JOIN sys.tables tab2
      ON tab2.object_id = fkc.referenced_object_id
     INNER JOIN sys.columns col2
      ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id
WHERE tab2.name = 'sometable'

declare @sql varchar(max)
set @sql=''
select @sql=@sql+' select '+[column]+' from '+[table] from tmpTable +' union all'

set @sql=substring(@sql,1,len(@sql)-9)

exec(@sql)

答案 1 :(得分:0)

我动态创建SELECT并在CURSOR内执行它们(极少数情况下,光标是一个不错的选择):

如果命令是您需要的,请使用打印来检查。然后在EXEC之前取消双减去以执行它们。

DECLARE @cmd VARCHAR(MAX);
DECLARE cur CURSOR FOR 
    SELECT 'SELECT ' + [column] + ' FROM ' + [table] + ';' 
    FROM @tmpTable;
OPEN cur;

FETCH NEXT FROM cur INTO @cmd;
WHILE @@FETCH_STATUS=0
BEGIN
    PRINT @cmd;
    --EXEC(@cmd)
    FETCH NEXT FROM cur INTO @cmd;
END
CLOSE cur;
DEALLOCATE cur;