简体   繁体   English

T-SQL (Azure Synapse) 基于未知数量主键的动态分组

[英]T-SQL (Azure Synapse) Dynamic grouping based on unknown number of Primary Keys

I'm tasked with creating a sp that will loop through every table in a supplied schema and find any that do not have unique primary keys (duplicate primary keys).我的任务是创建一个 sp,它将遍历提供的架构中的每个表,并找到任何没有唯一主键(重复主键)的表。 Some tables may have only one column creating the primary key while others may have composite keys with an unknown number of columns.一些表可能只有一列创建主键,而另一些表可能有包含未知列数的复合键。

For example:例如:

CREATE DATABASE test
USE TEST
CREATE PROC duplicateCheck @schemaChoice nvarchar(60)= 'test'
CREATE TABLE onePrimary(

      id int,
      orders int,
      orderCustomer varchar(20)
      PRIMARY KEY (id)
    )
CREATE TABLE twoPrimary(
      id int,
      item int,
      color varchar(20),
      size varchar(20),
      PRIMARY KEY(id,item)
    )
INSERT INTO onePrimary
VALUES(1,2,'Brad'),
(2,1,'Lenny'),
(3,1,'Rachel')

INSERT INTO twoPrimary
VALUES(1,1,'yellow','large'),
(2,1,'blue','small')


create table #primaryKey(
       TABLE_NAME varchar(20),
       COLUMN_NAME varchar(20)
    )
SELECT @schemaChoice,
       x.TABLE_NAME,
       x.COLUMN_NAME,
    FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE x, INFORMATION_SCHEMA.TABLE_CONSTRAINTS y
    WHERE x.TABLE_SCHEMA = @schemaChoice
    and y.CONSTRAINT_TYPE like 'PRIMARY KEY'

That's where I get stuck.这就是我卡住的地方。

You can find this information in Sql Server (and Azure Synapse) using the system views.您可以使用系统视图在 Sql 服务器(和 Azure Synapse)中找到此信息。

The following will list all user tables, the name of the primary key and how many key columns are defined.下面将列出所有用户表、主键名称以及定义了多少键列。

select Schema_Name(t.schema_id) SchemaName, t.name TableName, i.name PrimaryKey, Count(*) KeyColumnCount
from sys.tables t
join sys.indexes i on i.object_id = t.object_id and i.is_primary_key = 1
join sys.index_columns ic on ic.object_id = t.object_id and ic.index_id = i.index_id
group by t.name, i.name, Schema_Name(t.schema_id)
order by KeyColumnCount

You can add having count(*)>1 after the group by to only list tables with more than 1 key column, and of course any other filtering you need.您可以在group by之后添加having count(*)>1以仅列出具有超过 1 个键列的表,当然还有您需要的任何其他过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM