查询以从特定 table 收集所有索引并生成删除命令
Query to collect all indexes from a specific table and generate the drop command
我正在尝试为 select 来自特定 table 的所有索引编写一些代码,并输出命令以删除它们,我认为是这样的,但语法不正确全部。谁能帮忙?谢谢!
SELECT
'DROP INDEX ' + i.* + ' ON ' + TableName = t.Name
+ ';'
FROM
sys.indexes i
INNER JOIN sys.tables t ON t.object_id = i.object_id
WHERE
T.Name = 'TableXYZ';
我认为这会给出预期的结果。
SELECT 'DROP INDEX ' + i.name + ' ON ' + t.Name + ';' as sql_drop
FROM sys.indexes i
INNER JOIN sys.tables t ON t.object_id = i.object_id
WHERE T.Name = 'test'
and i.name is not null;
您也可以使用 CONCAT 连接:
SELECT concat('DROP INDEX ',i.name,' ON ',t.Name,';') as sql_drop
FROM sys.indexes i
INNER JOIN sys.tables t ON t.object_id = i.object_id
WHERE T.Name = 'test'
and i.name is not null;
您 必须 还添加 QUOTENAME
以便正确引用索引名称。您还应该指定架构。
SELECT
'DROP INDEX ' + QUOTENAME(i.name) + ' ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.Name) + ';'
FROM
sys.indexes i
JOIN sys.tables t ON t.object_id = i.object_id
JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE
t.Name = 'TableXYZ';
我正在尝试为 select 来自特定 table 的所有索引编写一些代码,并输出命令以删除它们,我认为是这样的,但语法不正确全部。谁能帮忙?谢谢!
SELECT
'DROP INDEX ' + i.* + ' ON ' + TableName = t.Name
+ ';'
FROM
sys.indexes i
INNER JOIN sys.tables t ON t.object_id = i.object_id
WHERE
T.Name = 'TableXYZ';
我认为这会给出预期的结果。
SELECT 'DROP INDEX ' + i.name + ' ON ' + t.Name + ';' as sql_drop
FROM sys.indexes i
INNER JOIN sys.tables t ON t.object_id = i.object_id
WHERE T.Name = 'test'
and i.name is not null;
您也可以使用 CONCAT 连接:
SELECT concat('DROP INDEX ',i.name,' ON ',t.Name,';') as sql_drop
FROM sys.indexes i
INNER JOIN sys.tables t ON t.object_id = i.object_id
WHERE T.Name = 'test'
and i.name is not null;
您 必须 还添加 QUOTENAME
以便正确引用索引名称。您还应该指定架构。
SELECT
'DROP INDEX ' + QUOTENAME(i.name) + ' ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.Name) + ';'
FROM
sys.indexes i
JOIN sys.tables t ON t.object_id = i.object_id
JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE
t.Name = 'TableXYZ';