OUTPUT新增记录入库示例C#+存储过程

1.C#代码

        public int Insert(Entity model)
        {
            var parameters = new SqlParameter[]
                {
                    new SqlParameter("@ID",SqlDbType.Int){Value = model.ID}, 
                    new SqlParameter("@COL", SqlDbType.Int) {Value = model.COL}

                };
            parameters[0].Direction = ParameterDirection.Output;
            var parmetersList = new ArrayList(parameters);
            return ExecuteSPE("Porc_TableName_Add", parmetersList);
        }

        /// <summary>
        /// 处理存储过程
        /// </summary>
        /// <param name="spName">存储过程名</param>
        /// <param name="parameters">参数列表</param>
        /// <returns>存储过程的返回值</returns>
        protected virtual int ExecuteSPE(string spName, ArrayList parameters)
        {
            int reValue = 0;
            ExecuteSP(spName, parameters, out reValue);
            return reValue;
        }

        /// <summary>
        /// 处理存储过程
        /// </summary>
        /// <param name="spName">存储过程名</param>
        /// <param name="parameters">参数列表</param>
        /// <param name="reValue">返回值</param>
        protected virtual void ExecuteSP(string spName, ArrayList parameters, out int reValue)
        {
            reValue = 0;
            cmd.CommandText = spName;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandTimeout = 60;
            cmd.Parameters.Clear();
            if (parameters != null)
            {
                foreach (SqlParameter param in parameters)
                {
                    cmd.Parameters.Add(param);
                }
            }
            SqlParameter returnParam = new SqlParameter("returnVal", SqlDbType.Bit);
            returnParam.Direction = ParameterDirection.ReturnValue;
            cmd.Parameters.Add(returnParam);
            try
            {
                Open();
                cmd.ExecuteNonQuery();
                reValue = Convert.ToInt32(returnParam.Value);
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(
                    "\r\n方法异常【ExecuteSP(string spName, ArrayList parameters, out int reValue)】" + spName, e);
                throw new Exception(e.Message);
            }
            finally
            {
                Close();
            }
        }


2.存储过程

CREATE PROCEDURE [dbo].[Porc_TableName_Add]
(
@ID INT OUTPUT,
@COL INT

)
 AS 
 

	INSERT INTO dbo.TableName(COL)
	VALUES  (@COL)
	SET @ID = @@IDENTITY
	
	
	RETURN @ID


你可能感兴趣的:(存储过程)