使用information_schema.columns进行动态查询

时间:2019-09-23 10:17:25

标签: sql sql-server information-schema dynamic-queries

我想创建一个动态查询,该查询使用information_schema.columns视图删除每个表的重复项。稍后,数据工厂活动将提供tableName。有任何想法吗?用于创建应唯一的内容的列是“ specifiedColumn”列之前的列(按ordinal_position排序)。

我想象查询看起来像这样,以给出一个想法。但是,正如您最清楚地了解到的那样,我是第一次使用这种information_schema!

WITH cte AS (
    SELECT 
        *
        ,ROW_NUMBER() OVER (
            PARTITION BY 
            (SELECT COLUMN_NAME FROM [INFORMATION_SCHEMA].[COLUMNS] WHERE 
            TABLE_SCHEMA = 'schemaName' AND 
            TABLE_NAME = 'tableName' AND
            ORDINAL_POSITION <= (SELECT ORDINAL_POSITION FROM [INFORMATION_SCHEMA].[COLUMNS] WHERE 
                                TABLE_SCHEMA = 'schemaName' AND 
                                TABLE_NAME = 'tableName' AND column_name = 'specifiedColumn')
            )
            ORDER BY 
            (SELECT COLUMN_NAME FROM [INFORMATION_SCHEMA].[COLUMNS] WHERE 
            TABLE_SCHEMA = 'schemaName' AND 
            TABLE_NAME = 'tableName' AND
            ORDINAL_POSITION <= (SELECT ORDINAL_POSITION FROM [INFORMATION_SCHEMA].[COLUMNS] WHERE 
                                TABLE_SCHEMA = 'schemaName' AND 
                                TABLE_NAME = 'tableName' AND column_name = 'specifiedColumn')
            )
        ) row_num
     FROM 
        [schemaName].[tableName]
)
DELETE FROM CTE 
WHERE row_num > 1;

最诚挚的问候,

0 个答案:

没有答案