我正在尝试使用此代码来获取与数据库相关的信息。
脚本是---
DECLARE @USER_Name SYSNAME
DECLARE @Database_Name VARCHAR(255)
DECLARE @SQLQRY VARCHAR(2000)
DECLARE Database_Cursor CURSOR
FOR
SELECT '[' + NAME + ']' AS NAME
FROM master.dbo.sysdatabases
WHERE NAME IN ('Aaskiran')
ORDER BY NAME
OPEN Database_Cursor
FETCH NEXT
FROM Database_Cursor
INTO @Database_Name
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Database:' + @Database_Name
EXECUTE (
'SELECT Type, COUNT(*) As Objects FROM
' + @Database_Name + '.dbo.sysobjects
GROUP BY Type ORDER BY Type'
)
EXECUTE (
'SELECT name As Table_Name FROM
' + @Database_Name + '.dbo.sysobjects
WHERE type=''U'' ORDER BY name'
)
EXECUTE (
'SELECT name As Stored_Proc_Name FROM
' + @Database_Name + '.dbo.sysobjects
WHERE type=''P'' ORDER BY name'
)
DECLARE @Table_Name VARCHAR(255)
EXECUTE (
'DECLARE Table_Cursor CURSOR FOR SELECT name, USER_NAME(uid) FROM
' + @Database_Name + '.dbo.sysobjects
WHERE type=''U'' ORDER BY name'
)
OPEN Table_Cursor
FETCH NEXT
FROM Table_Cursor
INTO @Table_Name,
@User_Name
SET @SQLQRY = 'SELECT
SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE
object_id=OBJECT_ID(' + @Database_Name + '.[' + @User_Name + '].[' + @Table_Name + '])
AND (index_id=0 or index_id=1)'
WHILE @@FETCH_STATUS = 0
BEGIN
EXECUTE (@SQLQRY)
--EXECUTE('SELECT COUNT(*) AS ['+@Table_Name+'_Rows_Count] FROM '+@Database_Name+'. ['+@User_Name+'].['+@Table_Name+']')
--print('SELECT COUNT(*) AS ['+@Table_Name+'_Rows_Count] FROM '+@Database_Name+'.['+@User_Name+'].['+@Table_Name+']')
FETCH NEXT
FROM Table_Cursor
INTO @Table_Name,
@User_Name
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor
FETCH NEXT
FROM Database_Cursor
INTO @Database_Name
END
CLOSE Database_Cursor
DEALLOCATE Database_Cursor
但我收到错误
Msg 4104,Level 16,State 1,Line 1 多部分标识符" AasKiran。## MS_PolicyEventProcessingLogin ##。AADetails"无法受约束。
我已经搜索过此错误,但大部分链接都在加入。我没有在我的查询中得到问题,因为我还没有使用任何别名或进行任何类型的连接。
答案 0 :(得分:2)
您的错误是当您致电OBJECT_ID()
时,您没有用引号括起表格的名称。你应该使用:
SET @SQLQRY = 'SELECT
SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE
object_id=OBJECT_ID(''' + @Database_Name + '.[' + @User_Name + '].[' + @Table_Name + ']'')
AND (index_id=0 or index_id=1)'
虽然我还不太清楚你想要达到的目的。