动态SQL,包含字段中的表名

时间:2016-04-01 09:01:24

标签: sql-server tsql dynamic-sql

有没有办法生成动态sql语句,以便一个表中的字段值参与正在连接的表名?

以下是我要做的事情:

DECLARE @sql NVARCHAR(MAX) = N''
DECLARE @MainProc NVARCHAR(MAX) = N'dbo.MainProc'

SET @sql += N'SELECT ref.*
FROM sys.dm_sql_referenced_entities (' + @MainProc + N', ''OBJECT'') AS ref
INNER JOIN ' + ref.referenced_database_name + '.sys.objects AS o ON ref.referenced_id = o.object_id AND o.type = ''P''
WHERE ref.referenced_schema_name NOT IN (''system'')'

EXEC sp_executesql @sql

如何将 ref.referenced_database_name 的值附加到 sys.objects

1 个答案:

答案 0 :(得分:2)

是的,稍微重构一下。在您的原始示例中,您尝试在查询之前从dm_sql_referenced_entities中提取值。

DECLARE @sql        NVARCHAR(MAX) = N''
DECLARE @MainProc   NVARCHAR(MAX) = N'Fact.Account_Load'

/* Builds the sys.Objects query.
 * Can return multiple queries.
 */
SELECT      
    @sql += 
    '
        SELECT
            s.*
        FROM
            ' + QUOTENAME(ref.referenced_database_name) + '.sys.objects AS s
        WHERE
            s.Object_Id = ' + CAST(ref.referenced_id AS VARCHAR(255)) + '
            AND s.Type = ''P''
        ;
    '
FROM
    sys.dm_sql_referenced_entities('Fact.Account_Load', 'OBJECT') AS ref
WHERE
    ref.referenced_database_name IS NOT NULL
GROUP BY
    ref.referenced_database_name,
    ref.referenced_id
;

-- Executes dynamic query.
EXECUTE(@sql);