查询应返回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')
输出:
+ - 数据库名 - + ---- ---- Last_user_SCAN +
| __ ALRT _ __ _ __ _ _ | _ 2013年8月30日1:47 PM_ |
答案 0 :(得分: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+''')'