使用select& amp;将数据插入表格执行程序

时间:2014-02-04 06:23:58

标签: sql sql-server stored-procedures sql-server-2008-r2

我想使用select语句和执行过程将数据插入表中。

那就是......假设一个表'TEMP'有4列A,B,C,D。 A& B列值将来自SELECT语句,C,D列值将通过执行任何存储过程来实现。

我试过以下但没有遇到错误。

INSERT INTO TEMP
SELECT R1.A, R1.B, R2.C, R2.D FROM 
(SELECT A , B FROM SOME_TABLE) AS R1
CROSS JOIN EXEC [dbo].[SOME_PROCEDURE] @SOME_VARIABLE1 ) AS R2

错误是:

Incorrect syntax near the keyword 'exec'

2 个答案:

答案 0 :(得分:1)

检查一下......

declare @var int

    exec EXEC [dbo].[SOME_PROCEDURE] @SOME_VARIABLE1,@output=@var


    INSERT INTO TEMP
    SELECT R1.A, R1.B, R2.C, R2.D FROM 
    (SELECT A , B FROM SOME_TABLE) AS R1
    CROSS JOIN @var) AS R2

答案 1 :(得分:0)

您无法在JOIN中使用存储过程。首先在临时表中存储存储过程的结果集,然后在JOIN中使用此临时表。

-- First create the table to which we want to push the SP result
CREATE TABLE #TempTableName(..........)

-- Insert result from the SP to temp table
INSERT INTO #TempTableName
EXEC [dbo].[SOME_PROCEDURE] @SOME_VARIABLE1 

然后进行加入

INSERT INTO TEMP
SELECT R1.A, R1.B, R2.C, R2.D FROM 
(SELECT A , B FROM SOME_TABLE) AS R1
CROSS JOIN #TempTableName AS R2