开发者

Joining two columns from sys.database table, etc

I am trying to join two tables. One being the sys.databases table and the other being a table defined in each database.

I am trying to gather the name of each database and the date it was created from the sys.databases table. [NAME] AND [CREATE_DATE]

The other column that I am trying to query on is from a different table called filesize, upon which I want to use the sum function to calculate the size of each database.

The problem that I am getting is that there is constant repetition. There should only be approximately 40 records to appear.

Here is my script:

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), CRE开发者_高级运维ATE_DATE, 101)
HAVING SUM(TOTAL_IMGSIZE_IN_MBS/1048576) IS NOT NULL
ORDER BY DBNAME


In your dynamic script you filter SYS.DATABASES on CREATE_DATE only.

I think you should add filtering by NAME too, i.e. add to the WHERE clause something like this:

'...AND NAME='''+@DBNAME+''' GROUP BY etc...'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜