从同一结构表中选择数据

时间:2016-09-19 17:29:35

标签: sql sql-server select sql-server-2014

我有这样的表格格式:

CODE    DESIGNER    BRAND   GENDER  SIZE    UNIT    TYPE    TOT
M1001      JOE       DIDI     M      1.9     oz      HH      88 

有相同格式的一千多个表。每一行都有一个独特的代码。 该CODE将出现在每个表中。我想在这个表中使用这个唯一的CODE来获取行。输出假设如下:

CODE    DESIGNER    BRAND   GENDER  SIZE    UNIT    TYPE    TOT
M1001      JOE       DIDI     M      1.9     oz      HH      98 
M1001      JOE       DIDI     M      1.9     oz      HH      88 
M1001      JOE       DIDI     M      1.9     oz      HH      78 
M1001      JOE       DIDI     M      1.9     oz      HH      48 

我的软件是SQL sever 2014。

1 个答案:

答案 0 :(得分:0)

使用动态sql的临时表到目前为止最容易看到"超过一千个表" ....

这是一个代码块,它将检索其中包含8列的所有表的名称,然后在每个表中搜索CODE = M1001,如果存在,则将记录放入临时表中,然后选择所有的结果......

IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    BEGIN
        DROP TABLE #Results
    END

CREATE TABLE #Results (
    AutoID INT IDENTITY(1,1)
    ,Code CHAR(5)
    ,Designer VARCHAR(15)
    ,Brand VARCHAR(15)
    ,Gender CHAR(1)
    ,Size DECIMAL(3,1)
    ,Unit VARCHAR(5)
    ,Type CHAR(2)
    ,TOT INT
)

DECLARE @TableName NVARCHAR(513)

DECLARE CursorName CURSOR FOR
SELECT
    QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name) as TableName
FROM
    sys.columns c
    INNER JOIN sys.tables t
    ON c.object_id = t.object_id
WHERE
    c.name IN ('CODE','DESIGNER','BRAND','GENDER','SIZE','UNIT','TYPE','TOT')
GROUP BY
    QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name)
HAVING
    COUNT(DISTINCT c.name) = 8

OPEN CursorName

FETCH NEXT FROM CursorName
INTO @TableName

    WHILE @@FETCH_STATUS = 0
    BEGIN

        DECLARE @SQL NVARCHAR(MAX)
        SET @SQL = '
        INSERT INTO #Results (Code,Designer,Brand,Gender,Size,Unit,Type,TOT)
          SELECT *
          FROM
             ' + @TableName + '
          WHERE
             CODE = ''M1001'''

          EXECUTE (@SQL)

        FETCH NEXT FROM CursorName
        INTO @TableName
    END

CLOSE CursorName
DEALLOCATE CursorName


SELECT *
FROM
    #Results