存储过程需要参数 'Incorrect syntax near ':'.'

Stored procedure expects parameter 'Incorrect syntax near ':'.'

我在 SQL 服务器中有以下存储过程:

CREATE PROCEDURE [PROC_SET_BRN_RPT_STSTC]  
    @I_RPT_I varchar(max),
    @I_MSTR_TBL varchar(max)
AS 
BEGIN
    DECLARE
        @VD_PSTG_D datetime2(0),
        @V_SQL varchar(4000),
        @BMG_RPT_I varchar(5) = ISNULL(@I_RPT_I, '') + 'M',
        @MAM_RPT_I varchar(5) = ISNULL(@I_RPT_I, '') + 'P';

    /*vd_pstg_d   :=  GET_DATE ('TDTD');*/
    SELECT @VD_PSTG_D = max(TIME_DIMN.DATE_D)
    FROM TIME_DIMN
    WHERE TIME_DIMN.TME_DIMN_I IN ( 'TDTD', 'TDSH' );

    DECLARE @SQLString NVARCHAR(500); 
    SET @SQLString = 'Delete From RPT_STSTC Where TXN_PSTG_D = :1 and Rpt_i = :2';
    Execute sp_executesql @SQLString, @vd_pstg_d, @I_Rpt_I;

    IF @@TRANCOUNT > 0
        COMMIT TRANSACTION;

当我尝试执行存储过程时,出现以下错误:

Incorrect syntax near ':'.

你知道会出现什么问题吗?

:1 和 :2 是问题所在。

你想在那里填充变量,但那是错误的方法。您需要在那里使用变量,不能像在其他语言中那样使用占位符。

SET @SQLString = 'Delete From RPT_STSTC Where TXN_PSTG_D =  @vd_pstg_d and Rpt_i = @I_Rpt_I';

T-SQL中不存在 :1 和 :2 的语法。

正如您的问题的评论中所指出的,此存储过程中不需要动态 SQL。你可以重写它:

CREATE PROCEDURE [PROC_SET_BRN_RPT_STSTC]  
    @I_RPT_I varchar(max),
    @I_MSTR_TBL varchar(max)
AS 
BEGIN
    DECLARE
        @VD_PSTG_D datetime2(0),
        @V_SQL varchar(4000),
        @BMG_RPT_I varchar(5) = ISNULL(@I_RPT_I, '') + 'M',
        @MAM_RPT_I varchar(5) = ISNULL(@I_RPT_I, '') + 'P';

    /*vd_pstg_d   :=  GET_DATE ('TDTD');*/
    SELECT @VD_PSTG_D = max(TIME_DIMN.DATE_D)
    FROM TIME_DIMN
    WHERE TIME_DIMN.TME_DIMN_I IN ( 'TDTD', 'TDSH' );

    DELETE FROM RPT_STSTC 
    WHERE TXN_PSTG_D = @vd_pstg_d AND Rpt_i = @I_Rpt_I;

    IF @@TRANCOUNT > 0
        COMMIT TRANSACTION;

仅在您绝对需要使用它时才使用 sp_executesql - 这里您不需要它。

只是为了回答您的问题,您可以这样做(但在这种简单情况下不建议这样做):

CREATE PROCEDURE [PROC_SET_BRN_RPT_STSTC]  
    @I_RPT_I varchar(max),
    @I_MSTR_TBL varchar(max)
AS 
BEGIN
    DECLARE
        @VD_PSTG_D datetime2(0),
        @V_SQL varchar(4000),
        @BMG_RPT_I varchar(5) = ISNULL(@I_RPT_I, '') + 'M',
        @MAM_RPT_I varchar(5) = ISNULL(@I_RPT_I, '') + 'P';

    /*vd_pstg_d   :=  GET_DATE ('TDTD');*/
    SELECT @VD_PSTG_D = max(TIME_DIMN.DATE_D)
    FROM TIME_DIMN
    WHERE TIME_DIMN.TME_DIMN_I IN ( 'TDTD', 'TDSH' );

    DECLARE @SQLString NVARCHAR(500); 
    SET @SQLString = CONCAT('Delete From RPT_STSTC Where TXN_PSTG_D =''', @VD_PSTG_D, ''' AND Rpt_i=''', @I_RPT_I, '''');
    Execute sp_executesql @SQLString, @vd_pstg_d, @I_Rpt_I;

    IF @@TRANCOUNT > 0
        COMMIT TRANSACTION;