SQL 服务器查询合并游标输出

SQL Server query combine cursor output

我想将此查询的输出合并为一个 table,我应该使用什么 join/union 或其他东西?

DECLARE @name VARCHAR(1000)

DECLARE db_cursor CURSOR FOR 
SELECT name FROM MASTER.dbo.sysdatabases 

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @name  

WHILE @@FETCH_STATUS = 0  
BEGIN  
      select getdate() as [Date Time], DEFAULT_DOMAIN()[Domain], SERVERPROPERTY('MachineName') AS Server,@@servername as [Instance],@name AS [Database], *
      from sys.sysprocesses  

      FETCH NEXT FROM db_cursor INTO @name 
END 

CLOSE db_cursor  
DEALLOCATE db_cursor

可以使用变量 table 和临时变量 table 来解决。我使用了一个变量 table 你可以添加任意多的列。

DECLARE @process_table TABLE (
    [Date Time] datetime  NULL,
    Domain varchar(max) NULL,
     [Server] sql_variant NULL,
      Instance varchar(max) NULL,
       [Database] varchar(max) NULL 
);

DECLARE @name VARCHAR(1000)

DECLARE db_cursor CURSOR FOR 
SELECT name FROM MASTER.dbo.sysdatabases 

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @name  

WHILE @@FETCH_STATUS = 0  
BEGIN  
      Insert into @process_table([Date Time],Domain,[Server],Instance,[Database])
      select getdate() as [Date Time], DEFAULT_DOMAIN()[Domain], SERVERPROPERTY('MachineName') AS Server,@@servername as [Instance],@name AS [Database]
      from sys.sysprocesses

      FETCH NEXT FROM db_cursor INTO @name 
END 

CLOSE db_cursor  
DEALLOCATE db_cursor

Select * from @process_table