如何使用其他过程将数据插入存储过程中的临时表?

时间:2016-05-12 14:19:31

标签: sql-server stored-procedures entity

我想从过程1 AddID1向过程2 AddTempData插入数据。但我不能这样做。

create proc AddID1
as
begin
declare @TempData table
(
    ID int
)
insert into @TempData select P.Id from Product as P 
select * from @TempData
end

create proc AddTempData
as
begin
declare @TempDataID table
(
  IDTemp int
)
insert into @TempDataID exec AddID1 
select * from @TempDataID
end

1 个答案:

答案 0 :(得分:1)

以下是一个完整的工作示例。

至于你的代码......也许试试

insert into @TempDataID (IDTemp)
   exec AddID1 

但以下是工作示例:

/*  START TSQL CODE */

/*  Stored Procedure Definition */

Use Northwind
GO


IF EXISTS 
    (
    SELECT * FROM INFORMATION_SCHEMA.ROUTINES
    WHERE ROUTINE_TYPE = N'PROCEDURE' and ROUTINE_SCHEMA = N'dbo' and ROUTINE_NAME = N'uspOrderDetailsByCustomerId'  
    )
BEGIN
    DROP PROCEDURE [dbo].[uspOrderDetailsByCustomerId]
END


GO

CREATE Procedure dbo.uspOrderDetailsByCustomerId
(
  @CustomerID nchar(5)
)
AS

BEGIN

    SET NOCOUNT ON



        SELECT 
            c.CustomerID, c.CompanyName /*,c.ContactName,c.ContactTitle,c.[Address],c.City,c.Region,c.PostalCode,c.Country ,c.Phone,c.Fax */
        FROM 
            Customers c 
            JOIN Orders o ON c.CustomerID = o.CustomerID /* this join here just to provide extra rows for the example */
        WHERE 
            c.CustomerID = @CustomerID

END

现在填充,首先是#Temp表。

    IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
    begin
            drop table #TempCustomer
    end


    CREATE TABLE #TempCustomer
    ( 
      [CustomerID] nchar(5)
    , [CompanyName] nvarchar(40)
    )

INSERT INTO #TempCustomer ( [CustomerID] , [CompanyName])
exec dbo.uspOrderDetailsByCustomerId 'ALFKI'

Select * from #TempCustomer


    IF OBJECT_ID('tempdb..#TempCustomer') IS NOT NULL
    begin
            drop table #TempCustomer
    end

你也可以使用@Variable Table(就像你的例子)

declare @VariableTableCustomer table
    ( 
      [CustomerID] nchar(5)
    , [CompanyName] nvarchar(40)
    )

INSERT INTO @VariableTableCustomer ( [CustomerID] , [CompanyName])
exec dbo.uspCustomerByCustomerId 'ALFKI'

Select * from @VariableTableCustomer

我刚刚运行了所有代码(减去一行),它可以运行:

--drop proc AddID1
GO

create proc AddID1
as
begin
declare @TempData table
(
    ID int
)


insert into @TempData 
/*select P.Id from Product as P */
/* note, i'm commenting out the above line and using the below line since I don't have your db table/rows */
select 333 union all select 444 union all select 555


select * from @TempData
end


GO



/* make sure hte procedure works...as you desire..before trying to stuff it into a temp or varaible table */
EXEC AddID1

GO




--drop proc AddTempData
GO


create proc AddTempData
as
begin
declare @TempDataID table
(
  IDTemp int
)
insert into @TempDataID (IDTemp) exec AddID1 
select 'Inside_AddTempData' as MyPlace , * from @TempDataID
end

GO

EXEC AddTempData