从列值中选择名称为table的表

时间:2018-01-29 09:20:54

标签: sql sql-server

我有这个SQL查询

SELECT table_name 
INTO #LukaTestTable
FROM information_schema.columns
WHERE column_name = 'GUID'
ORDER BY TABLE_NAME ;

如何使用TABLE_NAME中的名称获取所有表中列GUID的值?

或者我能得到像这样的表吗?

TABLE_NAME GUID_VALUE

3 个答案:

答案 0 :(得分:1)

为了能够在知道所需的表之前查询表,必须使用动态查询。如果您有任意数量的表,在SQL Server中,您可以使用游标实现此目的:

DECLARE
    @column VARCHAR(256) = 'GUID',
    @table VARCHAR(256),
    @query VARCHAR(4000);

DECLARE #Tables CURSOR LOCAL FAST_FORWARD
FOR
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = @column
ORDER BY TABLE_NAME;

OPEN #Tables
FETCH NEXT FROM #Tables INTO @table

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @query = 'SELECT ' + @column + ' FROM ' + @table
    EXEC(@query)

    FETCH NEXT FROM #Tables INTO @table
END

CLOSE #Tables
DEALLOCATE #Tables;

如果您确定自己的“指南”,请执行此操作。 column将具有相同的数据类型 - 您可以创建临时表并在WHILE循环中插入它,并在最后一次选择SELECT。

答案 1 :(得分:1)

您可以像这样使用动态SQL:

   declare @sql varchar(max) = cast (' ' as varchar(max));
    select @sql = @sql +
    (select ' select GUID from ' + quotename(table_name) + ' union all ' as 'text()'
    from #LukaTestTable
    for xml path('')); 

    set @sql = reverse(stuff(reverse(@sql), 1, 10, ''));
    --print @sql
    exec(@sql);

如果您想将table_name作为单独的列,则应先将其保存在#LukaTestTable

答案 2 :(得分:1)

使用While循环和动态Sql

尝试以下脚本
IF OBJECT_ID('tempdb..#GetSqlQuery') IS NOT NULL
DROP TABLE #GetSqlQuery
IF OBJECT_ID('tempdb..#GetSpecficcolumnvalue') IS NOT NULL
DROP TABLE #GetSpecficcolumnvalue
GO
CREATE TABLE #GetSqlQuery
(
ID INT IDENTITY
,SELECtQuery nvarchar(max)
,TableName varchar(200)
)

CREATE TABLE #GetSpecficcolumnvalue
(
ID INT IDENTITY
,GetValue nvarchar(max)
,TableName varchar(200)
)

INSERT INTO #GetSqlQuery(SELECtQuery,TableName)
SELECT 'SELECT GUID,'''+TABLE_NAME+''' As TableName FROM '+QUOTENAME(TABLE_NAME) AS SELECtQuery,QUOTENAME(TABLE_NAME) AS TableName
FROM( 
SELECT 
    TABLE_SCHEMA,
    TABLE_NAME,
    COLUMN_NAME 

FROM INFORMATION_SCHEMA.COLUMNS 
WHERE COLUMN_NAME ='GUID'   
)dt
ORDER BY TABLE_NAME


DEclare @MinId INt,@MaxId INT,@Sql nvarchar(maX),@TableName varchar(1000)
SELECT @MinId =MIN(Id),@MaxId=MAX(ID) FROM #GetSqlQuery
WHILE (@MinId<=@MaxId)
BEgin
SELECT @Sql=SELECtQuery ,@TableName=TableName   From  #GetSqlQuery WHERE ID=@MinId

PRINT @Sql
INSERT INTO #GetSpecficcolumnvalue(GetValue,TableName)
EXEC (@Sql)
SET @MinId=@MinId+1
END

  SELECT  ROW_NUMBER()OVER(ORDER BY (SELECT 1)) AS Seq,GetValue,TableName 
   FROM 
   (
 SELECT *, ROW_NUMBER ()OVER(PArtition by GetValue,TableName    ORDER BY 
 TableName) AS dup FROM #GetSpecficcolumnvalue
  )dt where dt.dup=1