我正在尝试加入两个表格。一个是sys.databases表,另一个是每个数据库中定义的表。
我正在尝试从sys.databases表中收集每个数据库的名称及其创建日期。 [NAME]和[CREATE_DATE]
我试图查询的另一列是来自另一个名为filesize的表,我希望使用sum函数来计算每个数据库的大小。
我得到的问题是不断重复。应该只有大约40条记录出现。
这是我的剧本:
SET NOCOUNT ON
DECLARE @DBNAME NVARCHAR(MAX)
DECLARE @DBNAME1 NVARCHAR(MAX)
DECLARE @varSQL NVARCHAR(MAX)
DROP TABLE TEMPIMGCOUNTERSERVER3
CREATE TABLE TEMPIMGCOUNTERSERVER3
(DBNAME NVARCHAR(MAX),
TOTAL_IMGSIZE_IN_MBS INT,
CREATE_DATE DATETIME)
DECLARE DBNAME CURSOR FAST_FORWARD FOR
select name from sys.databases where [NAME] LIKE 'Z%' AND create_date between GETDATE()-9 AND GETDATE()-3
ORDER BY [Name]
--SELECT * FROM SYS.DATABASES ORDER BY CREATE_DATE
OPEN DBNAME
FETCH NEXT FROM DBNAME INTO @DBname
WHILE (@@FETCH_STATUS=0)
BEGIN
--SET @DBNAME1=('USE ['+ @DBNAME +']')
--EXEC SP_EXECUTESQL @DBNAME1
Set @varSQL='INSERT INTO TEMPIMGCOUNTERSERVER3 (DBNAME, TOTAL_IMGSIZE_IN_MBS, CREATE_DATE)
SELECT ''['+@DBNAME+']'' AS DBNAME, SUM(FILESIZE/1048576) AS TOTAL_IMGSIZE_IN_MBS, CREATE_DATE
FROM SYS.DATABASES, ['+@DBNAME+'].dbo.tbldoc WHERE CREATE_DATE BETWEEN GETDATE()-9 AND GETDATE()-3
GROUP BY NAME, CREATE_DATE'
EXEC SP_EXECUTESQL @varSQL
FETCH NEXT FROM DBNAME
INTO @DBNAME
END
CLOSE DBNAME
DEALLOCATE DBNAME
INSERT TEMPIMGCOUNTERSERVER3 (DBNAME, TOTAL_IMGSIZE_IN_MBS)
SELECT 'TOTAL_IMGSIZE_IN_MBS', SUM(TOTAL_IMGSIZE_IN_MBS) AS TOTAL_IMGSIZE_IN_MBS FROM TEMPIMGCOUNTERSERVER3
SELECT DISTINCT DBNAME, SUM(TOTAL_IMGSIZE_IN_MBS) AS TOTAL_IMGSIZE_IN_MBS, convert(VARCHAR(10), CREATE_DATE, 101) AS CREATE_DATE FROM TEMPIMGCOUNTERSERVER3
GROUP BY DBNAME, convert(VARCHAR(10), CREATE_DATE, 101)
HAVING SUM(TOTAL_IMGSIZE_IN_MBS/1048576) IS NOT NULL
ORDER BY DBNAME
答案 0 :(得分:1)
在动态脚本中,您只能在SYS.DATABASES
上过滤CREATE_DATE
。
我认为您也应该按NAME
添加过滤,即添加WHERE
子句,如下所示:
'...AND NAME='''+@DBNAME+''' GROUP BY etc...'