我正在 SQL Server 中寻找一个查询,该查询将返回特定架构中所有表中给定年份的总行数,在本例中为dbo
.
此模式中的所有表都有一个名为的列,该列UPDT_TS
存储上次更新行的时间,可用于此日期计算。
我正在 SQL Server 中寻找一个查询,该查询将返回特定架构中所有表中给定年份的总行数,在本例中为dbo
.
此模式中的所有表都有一个名为的列,该列UPDT_TS
存储上次更新行的时间,可用于此日期计算。
假设你有一个 Results 表要插入记录,你可以用一个简单的游标来做到这一点:
DECLARE @Iterator varchar(255)
,@strSQL varchar(MAX)
DECLARE xyz CURSOR CURSOR FAST_FORWARD READ_ONLY
FOR
SELECT t.name
FROM sys.schemas s
JOIN sys.tables t
ON s.schema_id = t.schema_id
WHERE s.name = 'dbo'
OPEN xyz
FETCH NEXT FROM xyz
INTO @Iterator
WHILE @@FETCH_STATUS = 0
BEGIN
SET @strSQL = 'INSERT INTO Results
SELECT COUNT(*) as Rows, '''+@Iterator+''' as TableName
FROM '+QUOTENAME(@Iterator)+'
WHERE YEAR(UPDT_TS) = 2013
'
EXEC (@strSQL)
FETCH NEXT FROM xyz
INTO @Iterator
END
CLOSE xyz
DEALLOCATE xyz
GO
每当处理动态 sql 时,更改以确保您已确定语法会EXEC (@strSQL)
很有帮助PRINT (@strSQL)
。
您可以使用简单的游标和动态 SQL。
declare @v_Year int
set @v_Year = 2013
declare @v_TableName nvarchar(256)
declare @v_SQL nvarchar(max)
declare @v_Count int
declare @v_ResultTable table
(
TableName nvarchar(256),
[RowCount] int
)
declare cur cursor local fast_forward read_only for
select t.name from sys.tables as t
inner join sys.columns as c on t.object_id = c.object_id
where c.name = 'UPDT_TS' and t.schema_id = schema_id('dbo')
open cur
while (1=1)
begin
fetch next from cur into @v_TableName
if @@FETCH_STATUS <> 0
break;
set @v_SQL = 'select @v_Count = count(*) from '+QUOTENAME(@v_TableName)+' where year(UPDT_TS) = ' + cast(@v_Year as nvarchar(4))
exec sp_executesql @v_SQL, N'@v_Count int output', @v_Count output
insert into @v_ResultTable
select @v_TableName, @v_Count
end
close cur
deallocate cur
select * from @v_ResultTable
编辑 刚刚看到山羊的回答后发布:) 看起来我们有同样的想法:)
这也将起作用:
DECLARE @sql NVARCHAR(max)
,@year INT
SET @year = 2013
SELECT @sql = 'select sum (total) from (' + SUBSTRING(cast((
SELECT ' union select count(*) as Total
from ' + quotename(table_name) + '
where
UPDT_TS between dateadd(year,@year-1900,0) and dateadd(s,-1,dateadd(year,@year-1900+1,0))'
FROM information_schema.columns
WHERE column_name = 'UPDT_TS'
AND TABLE_SCHEMA = 'dbo'
FOR XML path('')
) AS NVARCHAR(max)), 8, 8000) + ') as Presum'
PRINT @sql
EXEC sp_executesql @sql
,N'@year int'
,@year = @year