我正在尝试使用SQL 2008 R2检查数据库中的索引碎片。
我正在使用以下代码,取自http://msdn.microsoft.com/en-gb/library/ms189858(v=sql.100).aspx并进行了一些名称更改:
USE StockSystem;
GO
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(), OBJECT_ID(N'dbo.StockItems'),NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;
GO
当我运行它时,我收到错误:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '('.
有人可以找到我出错的地方吗?
奇怪的是,如果我调用两个函数(DB_ID和OBJECT_ID)并获取值,那么替换主select语句中的值,一切正常。为什么我不能在SELECT中使用这两个函数,按照MSDN?
为了回应Akrem的sugegstion,我也尝试了这个但是得到了同样的错误。
USE StockSystem;
GO
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID('StockSystem'), OBJECT_ID(N'dbo.StockItems'), NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;
对不起所有更新。我在带有数据库副本的SQL2012系统上尝试了相同的查询。这没有问题。我也尝试了相同的语句,但在不同的数据库上使用不同的名称但在同一个SQL实例上。这也有效。
我想这是数据库的问题,所以我已经将副本恢复到测试SQL实例中。为此还原的副本运行索引统计信息具有相同的问题。由于这是一个公司不能没有的生产数据库,因此我可以尝试其他方面的限制。
任何想法?
use StockSystem
declare @dbid SMALLINT
declare @objectid INT
select @dbid = DB_ID('StockSystem'), @objectid = OBJECT_ID(N'dbo.StockItems')
SELECT a.index_id,name,avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (@dbid,@objectid,NULL,NULL,NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;
答案 0 :(得分:15)
您的数据库可能设置为兼容级别80(SQL Server 2000),并且DB_ID和OBJECT_ID函数不能用作动态管理功能的参数。
您应该将兼容性级别更改为更新的内容,或者在查询之前使用变量:
USE StockSystem;
GO
DECLARE
@database_id INT = DB_ID(),
@object_id INT = OBJECT_ID(N'dbo.StockItems');
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (@database_id ,@object_id , NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;
答案 1 :(得分:0)
尝试添加数据库名称
DB_ID("DataBaseName")
更新:
请尝试这个并告诉它好像有效
USE StockSystem;
GO
select * from sys.dm_db_index_physical_stats(DB_ID(),null,null,null,null)