【发布时间】:2019-06-06 18:55:27
【问题描述】:
我发布了另一个问题here
但事实证明,我的问题的第一个解决方案更简单,而且我将设置我的计数设置为在错误的位置进行迭代。 真正的问题是,当我尝试迭代时,我构建数据库名称的值是错误的。
这是 Stack Overflow 上一位友好人士更正的代码,他们通知我发布第二个问题,以用不正确的声明格式澄清这个问题。
主要问题涉及这一行 [EDDS'+cast(@databasename as nvarchar(128))+'].[EDDSDBO].[Document]
--check if the #databases table is already present and then drop it
IF OBJECT_ID('tempdb..#databases', 'U') IS NOT NULL
drop table #databases;
--create the temp table as outside the loop
create table #databases(
ID INT IDENTITY,
ArtifactID VARCHAR(20) -- not sure of this ID's data type
)
--check if your temp table exists and drop if necessary
IF OBJECT_ID('tempdb..#temptable', 'U') IS NOT NULL
drop table #temptable;
--create the temp table as outside the loop
create table #temptable(
fileSize dec,
extractedTextSize dec
)
--this will allow the population of each database name
DECLARE @databasename sysname = ''
-- initialze to 1 so it matches first record in temp table
DECLARE @LoopOn int = 1;
--this will be the max count from table
DECLARE @MaxCount int = 0;
--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]
-- do insert here so it adds the ID column
INSERT INTO #databases(
ArtifactID
)
SELECT ArtifactID
FROM edds.eddsdbo.[Case]
where name like '%Review%'
-- sets the max number of loops we are going to do
select @MaxCount = COUNT(*)
FROM #databases;
while @LoopOn <= @MaxCount
BEGIN
-- your table has IDENTITY so select the one for the loop your on
(initalize to 1)
select @databasename = ArtifactID
FROM #databases
WHERE ID = @LoopOn;
--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
-- dont know/think this will work like this? If not you have to
use dynamic SQL
FROM [EDDS'+cast(@databasename as nvarchar(128))+'].[EDDSDBO].
[Document] ed
where ed.CreatedDate >= (select CONVERT(varchar,dateadd(d,- (day(getdate())),getdate()),106))
-- remove all deletes/etc and just add one to the @LoopOn and it will be selected above based off the ID
select @LoopOn += 1
end
-- Query the final values in the temp table after the iteration is complete
select filesize+extractedTextSize as Gigs
FROM #temptable
我收到一个错误
无效的对象名称'EDDS'+cast(@databasename as nvarchar(128))+'.EDDSDBO.Document'
如果我手动输入EDDS1111111.EDDSDBO.Document,它可以正常工作。
如果我设置 declare @databasename nvarchar(128) = 1111111 它也会破坏代码。
我认为该错误与我如何将其转换或将其添加到语句中有关。
感谢您提供的任何帮助
【问题讨论】:
-
FROM [EDDS'+cast(@databasename as nvarchar(128))+']是你的问题。您不能使用变量来替换对象的名称。如果必须,则需要使用动态 SQL;其中包含大量关于 SQL 注入的警告。
标签: sql-server iteration sql-server-2017 declare