1 回答
TA贡献1844条经验 获得超8个赞
使用not exists条件来测试重复项,如下所示。
insert into test.dbo.indexes (table_view, [columns], [type], index_name, index_id)
select table_view, [columns], [type], index_name, index_id
from (
select
schema_name(t.[schema_id]) + '.' + t.[name] as table_view
, substring(column_names, 1, len(column_names)-1) as [columns]
, case when i.is_primary_key = 1 then 'Primary_key'
when i.is_unique = 1 then 'Unique'
else 'Not_unique' end as [type]
, i.[name] as index_name
, i.index_id
from sys.objects t
inner join sys.indexes i
on t.[object_id] = i.[object_id]
cross apply (
select col.[name] + ', '
from sys.index_columns ic
inner join sys.columns col on ic.[object_id] = col.[object_id] and ic.column_id = col.column_id
where ic.[object_id] = t.[object_id]
and ic.index_id = i.index_id
order by col.column_id
for xml path ('')
) D (column_names)
where t.is_ms_shipped <> 1
and index_id > 0
) X
-- The following where clause prevents the insertion of duplicates
where not exists (
select 1
from test.dbo.indexes I
where I.table_view = X.table_view and I.[columns] = X.[columns] and I.[type] = X.[type] and I.index_name = X.index_name and I.index_id = X.index_id
);
order by注意:在语句中添加 an 没有任何好处insert,表本质上是无序的,order by如果顺序很重要,您必须在 select 上使用。
- 1 回答
- 0 关注
- 101 浏览
添加回答
举报