2

现在我有列出所有引用表的代码,而且我可以一一计算表中的引用。

查询一:

SELECT t.NAME AS TableWithForeignKey,
    c.NAME AS ForeignKeyColumn
FROM sys.foreign_key_columns AS fk
INNER JOIN sys.tables AS t
    ON fk.parent_object_id = t.object_id
INNER JOIN sys.columns AS c
    ON fk.parent_object_id = c.object_id
        AND fk.parent_column_id = c.column_id
WHERE fk.referenced_object_id = (
        SELECT object_id
        FROM sys.tables
        WHERE NAME = 'MAIN_TABLE'
        )

查询 2:

SELECT COUNT(MAIN_ID)
FROM MAIN_TABLE
INNER JOIN REF_TABLE_1
    ON MAIN_TABLE.ID = REF_TABLE_1.MAIN_ID

查询 3:

SELECT COUNT(MAIN_ID)
FROM MAIN_TABLE
INNER JOIN REF_TABLE_2
    ON MAIN_TABLE.ID = REF_TABLE_2.MAIN_ID

等等

是否可以在一个查询中使用它?

4

1 回答 1

0

我试图通过使用 sql 块语句而不是单个查询来解决它。如果能解决您的问题,请尝试使用。您也可以为它创建一个存储过程。

BEGIN
    CREATE TABLE #tempTable (TName NVARCHAR(100), FKey NVARCHAR(100), RCount BIGINT)

    INSERT INTO #tempTable(TName, FKey)
    SELECT t.NAME AS TableWithForeignKey, 
        c.NAME AS ForeignKeyColumn 
    FROM sys.foreign_key_columns AS fk 
    INNER JOIN sys.tables AS t 
        ON fk.parent_object_id = t.object_id 
    INNER JOIN sys.columns AS c 
        ON fk.parent_object_id = c.object_id 
            AND fk.parent_column_id = c.column_id 
    WHERE fk.referenced_object_id = ( 
            SELECT object_id 
            FROM sys.tables 
            WHERE NAME = ''MAIN_TABLE' 
            ) 

    SELECT * FROM #tempTable

    DECLARE tempT CURSOR FOR SELECT TName FROM #tempTable

    DECLARE @tn NVARCHAR(100)

    OPEN tempT

    FETCH NEXT FROM tempT INTO @tn

    WHILE @@FETCH_STATUS = 0
    BEGIN
        EXEC (N'UPDATE #tempTable SET RCount = (SELECT COUNT(*) FROM ' + @tn + ') WHERE TName =''' +  @tn + '''')

        FETCH NEXT FROM tempT INTO @tn
    END 
    CLOSE tempT;
    DEALLOCATE tempT;

    SELECT * FROM #tempTable
    DROP TABLE #tempTable

END
于 2012-09-10T04:40:26.533 回答