gpt4 book ai didi

sql-server - SQL Server : sp_MSforeachdb into single result set

转载 作者:行者123 更新时间:2023-12-02 12:52:11 25 4
gpt4 key购买 nike

我将归档以获取一个查询,该查询从所有数据库中提取一些数据并返回单个结果集。

现在我有以下内容:

DECLARE @command varchar(4000)
SELECT @command = '
USE [?]
SELECT
database_name = DB_NAME(database_id)
, log_size_mb = CAST(SUM(CASE WHEN type_desc = "LOG" THEN size END) * 8. / 1024 AS DECIMAL(8,2))
, row_size_mb = CAST(SUM(CASE WHEN type_desc = "ROWS" THEN size END) * 8. / 1024 AS DECIMAL(8,2))
, total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))
, Kostenstelle = (select value from sys.extended_properties WHERE name = "Kostenstelle")
FROM sys.master_files WITH(NOWAIT)
WHERE database_id = DB_ID()
GROUP BY database_id
'
EXEC sp_MSforeachdb @command

上面的代码将返回多个结果集。

结果应如下所示:

|database_name|log_size_mb|row_size_mb|Kostenstelle|
+-------------+-----------+-----------+------------+
|demoA | 12| 10| xxxx|
|demoB | 52| 12| xxxx|

最佳答案

收到同事的回复 - 1000 谢谢

DECLARE @command varchar(4000)
SELECT @command = '
USE [?]
SELECT
database_name = CAST(DB_NAME(database_id) AS VARCHAR(50))
, log_size_mb = CAST(SUM(CASE WHEN type_desc = "LOG" THEN size END) * 8. / 1024 AS DECIMAL(8,2))
, row_size_mb = CAST(SUM(CASE WHEN type_desc = "ROWS" THEN size END) * 8. / 1024 AS DECIMAL(8,2))
, total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(8,2))
, Kostenstelle = CAST((select value from sys.extended_properties WHERE name = "Kostenstelle") AS VARCHAR(10))
FROM sys.master_files WITH(NOWAIT)
WHERE database_id = DB_ID()
GROUP BY database_id
'

DECLARE @DatabasesKst TABLE
(
database_name VARCHAR(50),
log_size_mb DECIMAL(8,2),
row_size_mb DECIMAL(8,2),
total_size DECIMAL(8,2),
Kostenstelle VARCHAR(100)
)

INSERT INTO @DatabasesKst
EXEC sp_MSforeachdb @command

select * from @DatabasesKst

..

如果你想过滤掉一些数据库,你可以像这样用 IF/BEGIN/END 包裹“USE [?]”。

DECLARE @command varchar(4000)
SELECT @command = '
IF ''?'' NOT IN(''master'', ''model'', ''msdb'', ''tempdb'')
BEGIN
USE [?]


SELECT
(your select/from/where statement here)


END
'

关于sql-server - SQL Server : sp_MSforeachdb into single result set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30544351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com