强制输出查询一次显示DB_NAME()数据一次
我有一个查询,可以从表中选择所有索引并生成输出文本以单独删除它们。
我想将db_name()
info放在命令的开头,但此时每个索引下显示数据。
我以前尝试过选择,但没有成功。
有人可以帮我吗?查询和结果如下:
- 查询
SELECT
'USE ' + QUOTENAME(db_name()) + ';' + CHAR(13) +
'GO ' + CHAR(13) +
'DROP INDEX ' + QUOTENAME(i.name) + ' ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.Name) + ';' + CHAR(13) +
'GO'
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 = 'Queue';
- 我得到的结果(示例)
USE [master];
GO
DROP INDEX [PK_Queue] ON [dbo].[Queue];
GO
USE [master];
GO
DROP INDEX [I_001] ON [dbo].[Queue];
GO
USE [master];
GO
DROP INDEX [I_002] ON [dbo].[Queue];
GO
- 我想要的结果
USE [master];
GO
DROP INDEX [PK_Queue] ON [dbo].[Queue];
GO
DROP INDEX [I_001] ON [dbo].[Queue];
GO
DROP INDEX [I_002] ON [dbo].[Queue];
GO
I've got a query that selects all indexes from a table and generate an output text to drop them individually.
I want to put the DB_NAME()
info in the beginning of command for once, but at this moment the data is showed at every index drop.
I've tried to put a select before, but without success.
Could someone help me? Query and results are below:
- QUERY
SELECT
'USE ' + QUOTENAME(db_name()) + ';' + CHAR(13) +
'GO ' + CHAR(13) +
'DROP INDEX ' + QUOTENAME(i.name) + ' ON ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.Name) + ';' + CHAR(13) +
'GO'
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 = 'Queue';
- Results that I get (example)
USE [master];
GO
DROP INDEX [PK_Queue] ON [dbo].[Queue];
GO
USE [master];
GO
DROP INDEX [I_001] ON [dbo].[Queue];
GO
USE [master];
GO
DROP INDEX [I_002] ON [dbo].[Queue];
GO
- Results that I want
USE [master];
GO
DROP INDEX [PK_Queue] ON [dbo].[Queue];
GO
DROP INDEX [I_001] ON [dbo].[Queue];
GO
DROP INDEX [I_002] ON [dbo].[Queue];
GO
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
但是,为什么要打扰呢?如 @shreepat18所说,您几乎可以在SQL Server Management Studio中脚本脚本!
But, why bother? You can script almost everything in SQL Server Management Studio as @shreepat18 said!
您可以只使用
use
命令初始化一个变量,然后使用字符串串联添加drop index
命令。这在SQL Server 2017(String_agg()
)中更容易,但是您没有告诉我们您使用的版本,所以...You can just initialize a variable with the
USE
command, and then append theDROP INDEX
commands using string concatenation. This is easier in SQL Server 2017 (STRING_AGG()
), but you didn't tell us what version you use, so...