[英]How can I insert result from stored procedure to a new table?
I have a stored procedure that returns a SELECT
(can't convert it into a view because it does a little bit more than a SELECT
). 我有一个存储过程返回一个
SELECT
(无法将其转换为视图,因为它比SELECT
还要多)。 I want to store the results into a new non temporary table. 我想将结果存储到新的非临时表中。
So far this is what I've tried 到目前为止,这是我尝试过的
select *
into newTable
from (StoredProcedure) t
But it throws an error: 但这会引发错误:
Incorrect syntax near ')'.
')'附近的语法不正确。
EDIT: My SP is 编辑:我的SP是
CREATE PROCEDURE Soporte.ManejoSPs
@NombreSP nvarchar (200)
AS
declare @qry nvarchar (500)
IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = @NombreSP + 'Table')
BEGIN
set @qry = 'select top 0 into ' + @NombreSP + 'Table from (@NombreSP) t'
print @qry
exec(@qry)
END
declare @Ultima datetime
declare @Tabla nvarchar(200)
declare @Minutos int
Select @Minutos = Minutos, @Tabla = NombreTabla, @Ultima = UltimaVez from Soporte.ManejoSP where NombreSP = @NombreSP
If (datediff(mi, @Ultima, getdate()) > @Minutos)
BEGIN
set @qry = 'INSERT INTO ' + @Tabla + ' exec ' + @NombreSP
exec(@qry)
END
set @qry = 'Select * from ' + @Tabla
exec(@qry)
Note : The following will only work up until SQL Server 2008 R2. 注意 :以下内容仅适用于SQL Server 2008 R2。 For SQL Server 2012+ this will not work (requires
WITH RESULT SETS
, see here for some details on its specification). 对于SQL Server 2012+,这将不起作用(需要
WITH RESULT SETS
,有关其规范的一些详细信息,请参见此处 )。
If your stored procedure is called t
(in database db_name
and schema schema_name
) and the table newTable
doesn't exist yet: 如果您的存储过程名为
t
(在数据库db_name
和schema schema_name
),并且表newTable
还不存在:
SELECT
*
INTO
newTable
FROM
OPENROWSET (
'SQLNCLI',
'Server=localhost;Trusted_Connection=yes;',
'SET FMTONLY OFF; EXEC [db_name].[schema_name].t;'
);
If the server is a named instance, you need to supply the proper Server parameter ( ServerName\\Instance
). 如果服务器是命名实例,则需要提供适当的Server参数(
ServerName\\Instance
)。
For this to work, you need the execute following first to allow Ad Hoc Distributed Queries
. 为此,您需要首先执行以下命令以允许
Ad Hoc Distributed Queries
。 You only need to execute this once. 您只需要执行一次。
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
If the newTable
table already exists: 如果
newTable
表已经存在:
INSERT INTO newTable
EXEC t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.