我创建了一个
cursor
来查询模式中的所有表,使用where
条件获取总记录,然后insert
将此结果放入另一个表中
DECLARE @TableName VARCHAR(150), @TotalRecords int
DECLARE CURSOR_TABLENAME CURSOR FOR
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE [TABLE_SCHEMA] = 'dbo'
OPEN CURSOR_TABLENAME
FETCH NEXT FROM CURSOR_TABLENAME INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @TotalRecords = (SELECT COUNT(*) FROM @TableName WHERE TenantId = '')
INSERT INTO PAGINATION (TOTALRECORDS, TABLENAME, TENANTID) VALUES (TotalRecords, @TableName,'')
FETCH NEXT FROM CURSOR_TABLENAME INTO @TableName
END
CLOSE CURSOR_TABLENAME
DEALLOCATE CURSOR_TABLENAME
如何在Select中使用@TableName?
这就是我们所说的 XY 问题。您根本不需要
COUNT(*)
,也不需要 CURSOR
。只需从 sys
对象获取所有数据即可。例如,调整 Brent Ozar 在 How to count the number of rows in a table in SQL Server: 中的解决方案
SELECT s.name AS SchemaName,
t.name AS TableName,
SUM(p.rows) AS TableRows
FROM sys.schemas s
JOIN sys.tables t ON s.schema_id = t.schema_id
INNER JOIN sys.partitions p ON t.object_id = p.object_id
INNER JOIN sys.indexes i ON p.object_id = i.object_id
AND p.index_id = i.index_id
WHERE i.index_id < 2
GROUP BY s.name,
t.name;