首页 > 代码库 > 生成自定义ID

生成自定义ID

        #region 自动生成ID
        /// <summary>
        /// 自动生成ID
        /// </summary>
        /// <param name="Table_Name">表名</param>
        /// <param name="Pk_Name">关键字</param>
        /// <param name="Digit">位数</param>
        /// <param name="TitleMark">题头标志</param>
        /// <returns>新生成的编号</returns>
        public static string GetNewId(string Table_Name, string Pk_Name, int Digit, string TitleMark)
        {
            string strSql = "";
            strSql = "SELECT ISNULL(MAX(" + Pk_Name + "),0) FROM " + Table_Name; //查找表中最大编号
            try
            {
                string NewId;
                DataSet ds = DBComm.SQLServerOperater.ExecuteDataSet(strSql, "NewId");
                NewId = ds.Tables["NewId"].Rows[0][0].ToString();
                if (NewId != "0")
                {
                    NewId = (Convert.ToInt32(NewId.Substring(NewId.Length - Digit)) + 1).ToString();
                }
                else
                {
                    NewId = "1";
                }
                NewId = TitleMark + NewId.PadLeft(Digit, ‘0‘);
                return NewId;

            }
            catch (Exception ex)
            {
                DBComm.SQLServerOperater.DALErrMsg = ex.Message;
                return null;
            }

        }
        #endregion

 

        #region 生成带日期的自定义ID

        /// <summary>
        /// 生成带日期的自定义ID
        /// </summary>
        /// <param name="Table_Name">表名</param>
        /// <param name="Pk_Name">主键名</param>
        /// <param name="Digit">位数</param>
        /// <param name="TitleMark">题头标志</param>
        /// <returns></returns>
        public static string GetNewId_Date(string Table_Name, string Pk_Name, int Digit, string TitleMark)
        {
            string Date = GetSysDateTime().ToString("yyyyMMdd").Substring(2);
            string strSql = "SELECT ISNULL(MAX(" + Pk_Name + "),1) AS ID FROM " + Table_Name + " WHERE SUBSTRING(ID,2,6)=‘" + Date + "‘";
            string New_Id = "";
            try
            {
                New_Id = Pruivew.DBConn.SQLHelper.ExecuteSQLScalar(strSql).ToString();
                if (New_Id != "1")
                {
                    New_Id = TitleMark + (Convert.ToInt64(New_Id.Substring(2)) + 1).ToString();
                }
                else
                {
                    New_Id = TitleMark + Date + New_Id.PadLeft(Digit, ‘0‘);
                }
                return New_Id;
            }
            catch (Exception ex)
            {
                DBComm.SQLServerOperater.DALErrMsg = ex.Message;
                return null;
            }
        }
        #endregion
    }