消息137,级别15,状态2,行29必须声明标量变量“@ACTIVE_STATUS”

时间:2013-12-23 09:20:06

标签: sql-server

ALTER PROCEDURE [dbo].[S_EDIT_USER] (@DSA_CODE       VARCHAR(10),
                                     @REQUESTOR_DEPT VARCHAR(40),
                                     @ACTIVE_STATUS  INT,
                                     @MAKER_ID       VARCHAR(10),
                                     @MAKER_IP       VARCHAR(20),
                                     @ERROR_CODE     INT OUTPUT)
AS
  BEGIN
      DECLARE @CNT INT;
      DECLARE @SQL NVARCHAR(MAX);

      SELECT @CNT = COUNT(*)
      FROM   TMAS_UAM_USER_TMP
      WHERE  DSA_CODE = @DSA_CODE;

      IF @CNT > 0
        SET @ERROR_CODE = 1;
      ELSE
        SET @ERROR_CODE = 0;

      IF @REQUESTOR_DEPT = 'N'
        SET @REQUESTOR_DEPT = '';
      ELSE
        SET @REQUESTOR_DEPT = @REQUESTOR_DEPT;

      PRINT @REQUESTOR_DEPT;

      IF @ERROR_CODE = 0
        SET @SQL = 'INSERT INTO TMAS_UAM_USER_TMP (  
   DSA_CODE  
           ,DSA_NAME  
           ,DSA_CITY  
           ,DSA_PRODUCT  
           ,DSA_PHNO  
           ,DSA_MOBNO  
           ,DSA_RQSTR  
           ,DSA_RQSTR_DEPT  
           ,GROUP_ID  
           ,ACTIVE_STATUS  
           ,REQ_TYPE  
           ,LAST_LOGED_IN  
           ,CREATED_ID  
     ,CREATED_IP  
     ,CREATED_DATE  
           ,MAKER_ID  
           ,MAKER_IP  
           ,MAKER_DATE  
 ) SELECT DSA_COD  
     ,DSA_NAM  
     ,DSA_CTY  
     ,PRODUCT  
     ,DSA_PHO  
     ,DSA_MOB  
     ,REQUESTOR  
     ,' + @REQUESTOR_DEPT + '
     ,GROUP_ID  
     ,@ACTIVE_STATUS 
     ,1  
     ,LAST_LOG_DAT  
     ,CREATED_ID  
     ,CREATED_IP  
     ,CREATED_DATE  
     ,' + @MAKER_ID + '  
     ,' + @MAKER_IP + '  
     ,GETDATE()  
    FROM DSA_MST WHERE DSA_COD = ' + @DSA_CODE + ' and ';

      IF @REQUESTOR_DEPT = 'N'
        BEGIN
            SET @SQL = @SQL + 'REQUESTOR_DEPT is null';

            PRINT( 'If Query' + @SQL );
        END
      ELSE
        BEGIN
            SET @SQL = @SQL + 'REQUESTOR_DEPT = ''' + @REQUESTOR_DEPT + '''';

            PRINT( 'Else Query' + @SQL );
        END

      EXECUTE (@SQL);

      RETURN @ERROR_CODE;
  END 

1 个答案:

答案 0 :(得分:2)

外部变量和参数不在EXECUTE (@SQL);

的范围内

您需要使用sp_executesql代替并将其作为参数传递。

此外,您应该阅读SQL注入。如果@REQUESTOR_DEPT之类的参数来自不受信任的来源(例如用户输入),您可能会受到攻击,因为您只是将它们直接连接到查询中。