Here is the Function to increment the ID Field in Sql table with Initial Character
The below function will get the Tablename,Column name and Field Character(initial character) as a Parameter and return the Increment value with Field Character. Example to increment UserId, need to pass the table name, field name and character as "UI", then the function will return UI00001
public string Autoincrement(string TName, string CName, string FCode)
{
string Id = null;
string strSql = null;
string tmp = null;
sqlconn = sqlConnection();
strSql = "";
strSql = "select max(cast(substring(" + CName + ",3,10)as integer))+1 from " + TName + "";
SqlCommand SqlCmd = new SqlCommand(strSql, sqlconn);
if (sqlconn.State == ConnectionState.Closed)
sqlconn.Open();
if (string.IsNullOrEmpty(SqlCmd.ExecuteScalar().ToString()))
{
Id = FCode + "00001";
if (sqlconn.State == ConnectionState.Open)
sqlconn.Close();
return Id;
}
strSql = "";
strSql = SqlCmd.ExecuteScalar().ToString();
if (strSql.Length == 1)
tmp = FCode + "0000";
else if (strSql.Length == 2)
tmp = FCode + "000";
else if (strSql.Length == 3)
tmp = FCode + "00";
else if (strSql.Length == 4)
tmp = FCode + "0";
else
tmp = FCode;
tmp = tmp + strSql;
Id = tmp;
if (sqlconn.State == ConnectionState.Open)
sqlconn.Close();
return Id;
}
Call the above function as
string userid = Autoincrement("tblUser","UserId","UI");
Thursday, September 10, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment