0

查询应返回 table = 'alrt' 的结果,
但在转义引号时出错

declare @dbname nvarchar(max)  
declare @query nvarchar(max)  
set @dbname = 'alrt'  
set @query ='SELECT OBJECT_NAME(object_id) AS DatabaseName, last_user_update,convert(nvarchar(max),last_user_seek),last_user_scan,last_user_lookup,last_system_update FROM sys.dm_db_index_usage_stats WHERE database_id = DB_ID ('+'''Frontoffrob'''+') AND OBJECT_ID=OBJECT_ID('+@dbname+')'
exec (@query)

错误结果

Msg 207, Level 16, State 1, Line 1 Invalid column name 'alrt'.

.
.
.
以下查询正在运行
SELECT OBJECT_NAME(object_id) AS DatabaseName,convert(nvarchar(max),last_user_scan)as SCAN FROM sys.dm_db_index_usage_stats WHERE database_id = DB_ID ('Frontoffrob') AND OBJECT_ID=OBJECT_ID ('ALRT')

输出:

+--DatabaseName--+----Last_user_SCAN----+
|__ ALRT _ __ _ __ _ | _ 2013 年 8 月 30 日下午 1:47_|

4

1 回答 1

1

在你的WHERE条款中使用这个:

'SELECT ... AND OBJECT_ID=OBJECT_ID('''+@dbname+''')'

实际上,您的查询应该如下所示:

set @query =
'SELECT 
    OBJECT_NAME(object_id) AS DatabaseName, 
    last_user_update,
    convert(nvarchar(max),last_user_seek),
    last_user_scan,
    last_user_lookup,
    last_system_update 
FROM sys.dm_db_index_usage_stats 
WHERE database_id = DB_ID (''Frontoffrob'') 
AND 
OBJECT_ID=OBJECT_ID(''' + @dbname+''')'
于 2013-08-30T05:59:54.100 回答