摘要:自動給號 範例
先在資料庫建一個資料表
欄位分別為 fId fKey fValue .
fId為P.K. type都設nvarchar(50)
01
public class CSerialNumberGen
02
{
03
private CDbManager iv_manager;
04
private CDbManager getManager() //連資料庫用的class,
05
{ // 1.queryBySql("查詢SQL指令")
06
if (iv_manager == null) //2. executeSql("執行SQL指令")
07
iv_manager = new CDbManager();
08
return iv_manager;
09
}
10
public int getNext(string p_strKey)
11
{
12
DataTable l_table = getManager().queryBySql("SELECT * FROM tTemp WHERE fKey='"+p_strKey+"'");
13
int l_int=1;
14
string l_str = "";
15
if (l_table.Rows.Count > 0) //如果有找到資料,把fValue加1,回填寫入資料庫
16
{
17
l_int = Convert.ToInt32(l_table.Rows[0]["fValue"].ToString()) + 1;
18
l_str = "UPDATE tTemp SET fValue='" + l_int.ToString() + "' WHERE fId='" + l_table.Rows[0]["fId"].ToString() + "'";
19
}
20
else //如果沒有找到資料,
21
{
22
l_str = "INSERT INTO tTemp (fId,fKey,fValue) VALUES (";
23
if ("tTemp".Equals(p_strKey)) //如果是第一次要號的話,fId=0
24
l_str += " '0', ";
25
else
26
l_str += " '" + getNext("tTemp").ToString() + "', "; //利用遞回的方式把fValue加1
27
l_str += " '" + p_strKey + "', ";
28
l_str += " '"+l_int.ToString()+"' )";
29
}
30
getManager().executeSql(l_str);
31
return l_int;
32
33
}
34
}
35
public class CSerialNumberGen02
{03
private CDbManager iv_manager;04
private CDbManager getManager() //連資料庫用的class,05
{ // 1.queryBySql("查詢SQL指令") 06
if (iv_manager == null) //2. executeSql("執行SQL指令")07
iv_manager = new CDbManager();08
return iv_manager;09
}10
public int getNext(string p_strKey)11
{12
DataTable l_table = getManager().queryBySql("SELECT * FROM tTemp WHERE fKey='"+p_strKey+"'");13
int l_int=1;14
string l_str = "";15
if (l_table.Rows.Count > 0) //如果有找到資料,把fValue加1,回填寫入資料庫16
{ 17
l_int = Convert.ToInt32(l_table.Rows[0]["fValue"].ToString()) + 1;18
l_str = "UPDATE tTemp SET fValue='" + l_int.ToString() + "' WHERE fId='" + l_table.Rows[0]["fId"].ToString() + "'"; 19
} 20
else //如果沒有找到資料,21
{22
l_str = "INSERT INTO tTemp (fId,fKey,fValue) VALUES (";23
if ("tTemp".Equals(p_strKey)) //如果是第一次要號的話,fId=0 24
l_str += " '0', "; 25
else26
l_str += " '" + getNext("tTemp").ToString() + "', "; //利用遞回的方式把fValue加127
l_str += " '" + p_strKey + "', ";28
l_str += " '"+l_int.ToString()+"' )";29
}30
getManager().executeSql(l_str);31
return l_int;32
33
}34
}35
使用方法例如: XXXX.getNext("資料表名稱").ToString("00000");
// 把要產生流水號的資料表放入getNext() 參數 ,ToString()參數放入 要從要產生的流水號 起始字串

