我有一个带有许多参数的存储过程。
我想像这样插入(或者选择):
INSERT INTO @TEMP_TABLE
EXECUTE STORED_PROCEDURE
未定义
@TEMP_TABLE
的模式。
例如:
declare @temptable2 as table
(
DatabaseName nvarchar(128),
dbsize nvarchar(128),
owner varchar(128),
dbid nvarchar(128),
created nvarchar(128),
status nvarchar(128),
compatibility_level nvarchar(128)
)
INSERT INTO @temptable2
EXEC ('sp_helpdb')
实现此目的的唯一方法是使用
SELECT INTO
#temp 表的古怪解决方法,这会带来更多麻烦,而不是值得的。
只需使用所需的列对表变量进行编码即可。 然后在两个存储过程中添加一个非常明显、位置良好的注释,提醒编码人员这种依赖性,然后继续进行其他工作。
CREATE PROCEDURE [dbo].[Sp_TestA](@P1 AS VARCHAR(50), @P2 AS VARCHAR(50),@P3 AS VARCHAR(50)) AS BEGIN
SELECT '1' AS Col1,@P1 AS Col2,@P2 AS Col3,@P3 AS Col4 UNION
SELECT '1' AS Col1,'A1' AS Col2,'A2' AS Col3,'A3' AS Col4 UNION
SELECT '2' AS Col1,'B1' AS Col2,'B2' AS Col3,'B3' AS Col4 UNION
SELECT '3' AS Col1,'C1' AS Col2,'C2' AS Col3,'C3' AS Col4 UNION
SELECT '4' AS Col1,'D1' AS Col2,'D2' AS Col3,'D3' AS Col4;
END
Declare @TblRtRcs TABLE(Col1 VARCHAR(50)NOT NULL,Col2 VARCHAR(50) NOT NULL,Col3 VARCHAR(50) NOT NULL,Col4 VARCHAR(50) NOT NULL);
DECLARE @Sql AS VARCHAR(MAX);
SET @Sql='EXEC [Sp_TestA @P1=''xA'',@P2=''xB'',@P3=''xC''';
INSERT INTO @TblRtRcs(Col1,Col2,Col3,Col4) EXEC(@Sql);
SELECT * FROM @TblRtRcs;
这个@skorpk 的答案实际上让我印象深刻,就像所问问题的正确答案一样。事实上,您可以按照问题所示插入表变量。此外,您还可以使用存储过程来做到这一点 期望参数。请参阅下面的示例代码:
这个答案实际上让我印象深刻,就像所问问题的正确答案一样。事实上,您可以按照问题所示插入表变量。此外,您还可以使用存储过程来做到这一点 期望参数。请参阅下面的示例代码:
/*Create stored procedure for this example. */
/*It will simulate results and we can clean it up */
/*later in this example */
create proc sproc_get_friends (@context_user_id int)
as
select @context_user_id as id, 'me' as name
union all select 1234678910 as id, 'Jane Doe' as name
union all select 1112131415 as id, 'John Doe' as name
go
/*Create temp variable*/
declare @tmp as table ( friend_user_id int, friend_name nvarchar(100) )
/*Insert into temp variable from stored procedure*/
INSERT INTO @tmp exec ('sproc_get_friends 10000')
/*Show data in temp variable*/
select * from @tmp
go
---Clean up
drop proc sproc_get_friends
go