SQL Server 如何在不声明临时表列的情况下将存储过程结果插入临时表

njthzxwz  于 2023-01-20  发布在  其他
关注(0)|答案(2)|浏览(239)

我想将存储过程的值插入到临时表中,而不预定义临时表的列。

Insert Into #Temp1 Exec dbo.sp_GetAllData @Name = 'Jason'.

我该怎么做?我看到下面的选项,但我可以不提服务器名称吗?

SELECT * INTO #TestTableT FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;',
'EXEC tempdb.dbo.GetDBNames')
-- Select Table
SELECT *
FROM #TestTableT;
68de4m5k

68de4m5k1#

如果不定义临时表模式和编写服务器名称,我无法找到可能的解决方案。因此,我更改了代码和查询,以便仅使用已知模式进行处理。代码示例如下

CREATE TABLE #TestTable ([name] NVARCHAR(256), [database_ID] INT);
    INSERT INTO #TestTable
    EXEC GetDBNames

    SELECT * FROM #TestTable;

如链接https://blog.sqlauthority.com/2013/05/27/sql-server-how-to-insert-data-from-stored-procedure-to-table-2-different-methods/中所提供

pepwfjgg

pepwfjgg2#

没人说一定要漂亮

CREATE PROCEDURE p AS
SELECT 1 as x, 2 as y, 3 as z
GO
DECLARE c CURSOR FOR
SELECT 
name, system_type_name
FROM sys.dm_exec_describe_first_result_set_for_object(OBJECT_ID('p'), 0);
DECLARE @name sysname, @type sysname;

CREATE TABLE #t(fake int)

OPEN c
FETCH NEXT from c into @name, @type
WHILE (@@FETCH_STATUS = 0)
BEGIN

 EXEC ('ALTER TABLE #t ADD ' + @name + ' ' + @type)
 FETCH NEXT from c into @name, @type
END

CLOSE C
DEALLOCATE c
ALTER TABLE #t DROP COLUMN fake;

INSERT INTO #t EXEC p;
GO

相关问题