将sp_executesql与临时表一起使用时,建议使用全局临时表

时间:2014-01-09 08:58:03

标签: sql-server tsql

我们使用带有变量和临时表的动态sql具有以下结构:

DECLARE @X AS INT = 1;
DECLARE @Y AS INT = 1;
DECLARE @Z AS INT = 1;

DECLARE @S AS NVARCHAR(500) = 
           N' SELECT @P+@Q+@R AS ANSWER INTO #X'

EXEC sp_executesql 
    @stmt   = @S,
    @params = N'@P AS INT,@Q AS INT,@R AS INT',
    @P  = @X,
    @Q  = @Y,
    @R  = @Z; 

SELECT (ANSWER + 1) AS FINALANSWER
FROM #X

临时表#x在范围sp_executesql中创建,因此无法在后续代码中使用该数据。

我需要采取标准方法来实现这项工作,还是应该切换到全局临时表?

2 个答案:

答案 0 :(得分:3)

我首先要创建临时表。内部执行范围可以查看外部范围的临时表:

DECLARE @X AS INT = 1;
DECLARE @Y AS INT = 1;
DECLARE @Z AS INT = 1;

CREATE TABLE #X (ANSWER INT)

DECLARE @S AS NVARCHAR(500) = 
           N'INSERT INTO #X(ANSWER) SELECT @P+@Q+@R'

EXEC sp_executesql 
    @stmt   = @S,
    @params = N'@P AS INT,@Q AS INT,@R AS INT',
    @P  = @X,
    @Q  = @Y,
    @R  = @Z; 

SELECT (ANSWER + 1) AS FINALANSWER
FROM #X

答案 1 :(得分:2)

使用OUTPUT参数查看此值以重新标记值

<强>程序

ALTER PROCEDURE SomeProc
@X INT = NULL,
@Y INT = NULL,
@Z INT = NULL,
@Result INT OUTPUT
AS
BEGIN
DECLARE @S AS NVARCHAR(MAX);

SET @S = N' SELECT @Result =  @X + @Y + @Z'

EXEC sp_executesql  @S
                   ,N'@X INT,@Y INT,@Z INT, @Result INT OUTPUT'
                   , @X, @Y, @Z, @Result OUTPUT 

END

执行Proc

DECLARE @R INT;
EXECUTE SomeProc 
@X = 1, 
@Y = 1, 
@Z = 1,
@Result = @R OUTPUT

SELECT @R + 1 AS FinalAnswer

<强>结果

FinalAnswer
4

修改

由于你在评论中提到过你将从proc中返回一个表格,在这种情况下我会建议在proc中做一个简单的SELECT并将你从proc返回的结果输入到Temp表中在proc之外。像这样......

IF OBJECT_ID('tempdb..#Results') IS NOT NULL 
DROP TABLE #Results
GO
CREATE TABLE #Results (Value INT)
GO

/* Execute Proc and insert into temp table */

INSERT INTO #Results (Value)
EXECUTE YourProc @Var1, @Var2 ....