动态SQL错误

时间:2017-09-02 00:29:07

标签: sql-server tsql

我正在尝试运行以下存储过程。

CREATE PROCEDURE NWR.GRADER 
    @YEAR AS NVARCHAR(4)
AS
BEGIN 
    DECLARE @sql1 as nvarchar(500) = 
        N'select a.*, b.pts as W_GRD_PTS
          into nwr.atp_matches_' + @YEAR + N'WGP
          from nwr.atp_matches_' + @YEAR + N' a 
          left join NWR.RNK_VAL as b on a.winner_rank >= low 
                                     and a.winner_rank<= high

          alter table nwr.atp_matches_' + @YEAR + N'WGP
             add L_GRD_PTS smallint  null

          UPDATE nwr.atp_matches_' + @YEAR + N'WGP
          SET L_GRD_PTS = C.pts 
          FROM NWR.RNK_VAL C 
          WHERE loser_rank >= LOW AND loser_rank <= HIGH;'

    --print (@sql1);
    EXEC sys.sp_execute @sql1;
end;

exec nwr.GRADER @year='2016';

但是我收到以下错误

  

Msg 214,Level 16,State 2,Procedure sp_execute,Line 1
  程序需要参数&#39; @ handle&#39;类型&#39; int&#39;。

但是当我切换到Print而不是EXEC时,我得到的代码与我预期的完全相同:

select a.*, b.pts as W_GRD_PTS
into nwr.atp_matches_2016WGP
from nwr.atp_matches_2016 a 
left join NWR.RNK_VAL as b on a.winner_rank >= low and a.winner_rank <= high

alter table nwr.atp_matches_2016WGP
    add L_GRD_PTS smallint  null

UPDATE nwr.atp_matches_2016WGP
SET L_GRD_PTS=C.pts 
FROM NWR.RNK_VAL C 
WHERE loser_rank>= LOW AND loser_rank<= HIGH;

任何人都可以解释我做错了吗?

1 个答案:

答案 0 :(得分:3)

错误的共鸣是您使用 sys.sp_execute 而不是 sys.sp_executesql

另一方面,我无法注意到您的动态查询看起来有点简化......只是把它扔出去......

CREATE PROCEDURE NWR.GRADER 
    @YEAR AS NVARCHAR(4),
    @Debug BIT = 0      -- 0=execute d-sql & 1=print d-sql...
AS
BEGIN 
    SET NOCOUNT ON;

    DECLARE @sql1 as nvarchar(500) =N'
SELECT 
    a.*, 
    W_GRD_PTS = b.pts,
    L_GRD_PTS = c.pts
    into nwr.atp_matches_' + @YEAR + N'WGP
FROM 
    nwr.atp_matches_' + @YEAR + N' a 
    LEFT JOIN NWR.RNK_VAL as b
        ON a.winner_rank >= b.low 
        AND a.winner_rank <= b.high
    LEFT JOIN NWR.RNK_VAL c
        ON a.loser_rank >= c.low 
        AND a.loser_rank<= c.high;'

    IF @Debug = 1
    BEGIN
        PRINT(@sql1);
    END;
    ELSE
    BEGIN 
        EXEC sys.sp_executesql @sql1;
    END;
END;
GO