T-SQL筆記30_取得特定DB(或所有DB)中tables佔有的儲存空間資訊_Cannot resolve collation conflict ... in UNION ALL operator occurring in SELECT statement column 1

 最近剛好研究一下it邦有個人發的問題

剛好有機會未來自己也會用的到
也就順帶研究並記錄了


議題就是



歷經千辛萬苦把這串T-SQL整理出來(其實關鍵在於怎麼跨DB陳列tables資訊)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
declare @sql nvarchar(max);
set @sql = '';--記得初始化
declare @tb_databases table (s_dbid int ,s_db_name nvarchar(50)) 
insert into @tb_databases  select dbid,name FROM master.dbo.sysdatabases
--select * from @tb_databases
declare @RowCnt BIGINT = 0;
set @RowCnt = (select COUNT(*)  'RowCount' from @tb_databases)
--print @RowCnt

declare @IdxRound BIGINT = 1;
--@RowCnt
while @IdxRound <= @RowCnt
begin	
	--print @IdxRound	
	declare @s_db_name nvarchar(max);
	set @s_db_name = (select s_db_name from @tb_databases where s_dbid=@IdxRound)
	--print @s_db_name

	declare @sql_tmp nvarchar(max);
	set @sql_tmp = N' select * from ( 
			SELECT 
			t.NAME AS TableName,
			--s.Name AS SchemaName,
			p.rows AS RowCounts,
			SUM(a.total_pages) * 8 /1024 AS TotalSpaceMB, 
			SUM(a.used_pages) * 8 /1024 AS UsedSpaceMB, 
			(SUM(a.total_pages) - SUM(a.used_pages)) * 8 /1024 AS UnusedSpaceMB
		FROM 
			target_db.sys.tables t
		INNER JOIN      
			target_db.sys.indexes i ON t.OBJECT_ID = i.object_id
		INNER JOIN 
			target_db.sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
		INNER JOIN 
			target_db.sys.allocation_units a ON p.partition_id = a.container_id
		LEFT OUTER JOIN 
			target_db.sys.schemas s ON t.schema_id = s.schema_id
		WHERE 
			t.is_ms_shipped = 0
		GROUP BY 
			t.Name, s.Name, p.Rows
			) as tb_result  ';
	--print REPLACE(@sql_tmp,'target_db',@s_db_name)
	set @sql_tmp = REPLACE(@sql_tmp,'target_db',@s_db_name);
	--exec sp_executesql @sql_tmp;
	
	if @IdxRound = @RowCnt
		begin
			set @sql = @sql + @sql_tmp;	
		end
	else
		begin
			set @sql = @sql + @sql_tmp + ' UNION ALL ';	
		end	
	set @IdxRound = @IdxRound + 1
end
--print @sql;
--SELECT CAST('<![CDATA[' + CAST(@sql as nvarchar(max)) + ']]>' as xml) --SSMS 顯示有文字長限制用這複製到note才可以看完整的
exec sp_executesql @sql;



只不過出現這個讓人有點錯愕的error message







那也追到某一個DB比較特立獨行的資料庫定序
若只是測試的 可以ByPass或刪除
若也要一併納入分析
則可能統一資料庫定序是較好的做法











Ref:

SQL語句進行left join的時候發生Cannot resolve collation conflict for equal to operation 錯誤

How to Resolve the collation conflict and check Collate in SQL Server


SQL SERVER – Cannot Resolve Collation Conflict For Equal to Operation


Cannot Resolve the Collation Conflict.
https://www.sqlcoffee.com/Troubleshooting075.htm



留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

(2021年度)駕訓學科筆試準備題庫歸納分析_法規是非題