syntax error in CROSS APPLY

ぐ巨炮叔叔 提交于 2019-12-12 08:22:41

问题


I'm trying to run a simple query to find the queries with the highest average CPU time. The code is literally copy-pasted from here:

SELECT TOP 5 total_worker_time/execution_count AS [Avg CPU Time],
    SUBSTRING(st.text, (qs.statement_start_offset/2)+1, 
        ((CASE qs.statement_end_offset
          WHEN -1 THEN DATALENGTH(st.text)
         ELSE qs.statement_end_offset
         END - qs.statement_start_offset)/2) + 1) AS statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
ORDER BY total_worker_time/execution_count DESC;

Problem is, SQL Server is complaining about a syntax error in line 8 at the parameter to sys.dm_exec_sql_text: qs.sql_handle which unhelpfully reads

Incorrect syntax near '.'.

I cannot, for the life of me, figure out what's wrong with the query. Any ideas?


回答1:


It means that you are either

  1. not running SQL Server 2005; or more likely
  2. not running in Compatibility mode 90 or above

You can change it to 90 or above using, but it could very well break a lot of applications.

alter database MyDataBaseName set compatibility_level = 90

The easiest solution on SQL Server 2005 and above is simply to run it from "master" or "tempdb", e.g.

USE tempdb;
SELECT TOP 5 total_worker_time/execution_count AS [Avg CPU Time],
    SUBSTRING(st.text, (qs.statement_start_offset/2)+1, 
        ((CASE qs.statement_end_offset
          WHEN -1 THEN DATALENGTH(st.text)
         ELSE qs.statement_end_offset
         END - qs.statement_start_offset)/2) + 1) AS statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
ORDER BY total_worker_time/execution_count DESC;


来源:https://stackoverflow.com/questions/13922540/syntax-error-in-cross-apply

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!