简体   繁体   English

创建具有表和数据库统计信息的表

[英]create a table with table and database statistics

There are around 200+ tables in our SQL DB and every table has 1 common field [updated_timestamp]我们的 SQL DB 中有大约 200 多个表,每个表都有 1 个公共字段 [updated_timestamp]

Is there a way to query the DB itself and list all tables, with the MAX value of [updated_timestamp] and the row count of each table?有没有办法查询数据库本身并列出所有表,其中 [updated_timestamp] 的 MAX 值和每个表的行数?

i'm sorry if i've not explained that the best对不起,如果我没有解释最好的

are there secret/system tables that hold such info?是否有包含此类信息的秘密/系统表?

my desired output would be我想要的 output 将是

table桌子 updated_timestamp更新时间戳 row_count行数
Table A表 A 2022-08-22 2022-08-22 89,854 89,854
Table B表 B 2022-08-18 2022-08-18 103,55,166 103,55,166

if there is a table like this i could intergate that would be great, but i'm assuming not that simple.如果有一张这样的桌子,我可以整合,那会很棒,但我假设不是那么简单。

i picked up some code from another stored procedure and was hoping this would be of use for the row count at least我从另一个存储过程中获取了一些代码,并希望这至少对行数有用

SELECT
      QUOTENAME(SCHEMA_NAME(sOBJ.schema_id)) AS [DB_Schema],
      QUOTENAME(sOBJ.name) AS [TableName],
      SUM(sPTN.Rows) AS [Row_Count]
INTO ##tmpRowCount2
FROM 
      sys.objects AS sOBJ
      INNER JOIN sys.partitions AS sPTN
            ON sOBJ.object_id = sPTN.object_id
WHERE
      sOBJ.type = 'U'
      AND sOBJ.is_ms_shipped = 0x0
      AND index_id < 2
GROUP BY 
      sOBJ.schema_id
      , sOBJ.name
ORDER BY [Row_Count]
GO

ALTER TABLE ##tmpRowCount2 ADD updated_timestamp datetime NULL;

-- keep only API rows
DELETE FROM ##tmpRowCount2
WHERE [DB_Schema] != '[api]'


DECLARE @Row_Count int
DECLARE @sql nvarchar(max)
DECLARE @TableName as VARCHAR(256)
DECLARE @DB_Schema as VARCHAR(256)
DECLARE @updated_timestamp as DATETIME
DECLARE tablenamefromcursor CURSOR FOR 

SELECT  TableName, 
        Row_Count, 
        DB_Schema
FROM ##tmpRowCount2
        
OPEN tablenamefromcursor

FETCH NEXT FROM tablenamefromcursor INTO  @TableName, @Row_Count, @DB_Schema
WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @sql = 'UPDATE ##tmpRowCount2  SET updated_timestamp = ' + 
            '(SELECT MAX([updated_timestamp]) FROM ' + @DB_Schema + '.' + @TableName + 
            ') WHERE TableName = ''' + @TableName + ''''
        
        EXEC(@sql)
        FETCH NEXT FROM tablenamefromcursor INTO  @TableName, @Row_Count, @DB_Schema
    END

CLOSE tablenamefromcursor
DEALLOCATE tablenamefromcursor

Code editied above and i can confirm it works, by debugging with select @sql iwas able to parse the statement and edit the syntax unitl it worked by getting the parethesis and quotes in the right order上面编辑的代码,我可以确认它有效,通过使用select @sql进行调试,我能够解析语句并通过以正确的顺序获取括号和引号来编辑它工作的语法

选择调试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM