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

时间:2017-03-23 18:45:30

标签: sql sql-server

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

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;

2 个答案:

答案 0 :(得分:1)

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

    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/

中所提供的那样

答案 1 :(得分:0)

没有人说它必须漂亮:

CREATE PROCEDURE p AS
SELECT 1 as x, 2 as y, 3 as z

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;