【发布时间】:2019-06-06 17:16:43
【问题描述】:
我正在查询某些数据库中最近数据的总大小。
我创建了一个包含要查询的数据库的表,然后对其进行迭代以获取数据库名称和运行迭代的总次数。
然后我创建一个临时表,将需要的数据插入其中。
我运行迭代以获取信息并将其推送到每个数据库的临时表中。
迭代完成后,我无法从这个新创建的表中提取值。
我在每个代码部分旁边写了一个小注释,解释了我正在尝试做什么以及我期望发生什么。
/*check if the #databases table is already present and then drop it*/
IF OBJECT_ID('tempdb..#databases', 'U') IS NOT NULL
begin
drop table #databases;
end
select ArtifactID into #databases from edds.eddsdbo.[Case]
where name like '%Review%'
/*Once this first statement has been run there will now be a
number column that is associated with the artificatID. Each database has an area that is
titled [EDDS'artifactID']. So if the artifactID = 1111111 then the DB would
be accessed at [EDDS1111111]*/
declare @runs int = 1; /*this will track the number of times iterated
over the result set*/
declare @max int = 0; /*this will be the limit*/
declare @databasename sysname='' /*this will allow the population of each
database name*/
/*check if your temp table exists and drop if necessary*/
IF OBJECT_ID('tempdb..#temptable', 'U') IS NOT NULL
begin
drop table #temptable;
end
/*create the temp table as outside the loop*/
create table #temptable(
fileSize dec,
extractedTextSize dec
)
while @runs<=@max
begin
select @max=count(*) from #databases;
/*the @max is now the number of databases inserted in to this table*/
/*This select statement pulls the information that will be placed
into the temptable. This second statment should be inside the loop. One time
for each DB that appeared in the first query's results.*/
/*begin the loop by assigning your database name, I don't know what the
column is called so I have just called it databasename for now*/
select top 1 @databasename = ArtifactID from #databases;
/*generate your sql using the @databasename variable, if you want to make
the database and table names dynamic too then you can use the same formula*/
insert into #temptable
select SUM(fileSize)/1024/1024/1024, SUM(extractedTextSize)/1024/1024
FROM [EDDS'+cast(@databasename as nvarchar(128))+'].[EDDSDBO].[Document] ed
where ed.CreatedDate >= (select CONVERT(varchar,dateadd(d,-
(day(getdate())),getdate()),106))'
/*remove that row from the databases table so the row won't be redone
This will take the @max and lessen it by one*/
delete from #databases where ArtifactID=@databasename;
/* Once the @max is less than 1 then end the loop*/
end
/* Query the final values in the temp table after the iteration is complete*/
select filesize+extractedTextSize as Gigs from #temptable
当最后的 select 语句运行以从 #temptable 中提取值时,响应是单个 gigs 列(如预期的那样),但表本身是空白的。
发生了一些事情来清除表格中的数据,我被卡住了。
我不确定我的错误是语法错误还是一般逻辑错误,但我们将不胜感激。
【问题讨论】:
-
除非我在运行时丢失了你所拥有的东西
-
把same question单独发到多个论坛是不礼貌和浪费的。
-
@SMor3 -- 有时一个人不知道在哪里发帖
-
SQL 中的“迭代”一词通常意味着一个人正在以计算机语言程序员的身份思考{e.g. C#} 而不是 SQL 程序员;尽管有时在 SQL 中需要迭代。但是,如果可能,请避免使用它们。
-
我接受过 JavaScript 培训,所以我的条件有点偏离。感谢您告知我有关术语和实践的信息。我可以看到它移动的速度有多慢,所以我会避免对更大的查询这样做。
标签: sql-server tsql iteration temp-tables sql-server-2017