关于SQL函数效率的一些测试与思考
上一篇 / 下一篇 2012-05-16 14:05:35 / 个人分类:数据库
;YKe4\)| J0 Student:
*?H2j'J1gi%[0Class:51Testing软件测试网0TR2~iP3n;U
-ZP/L5]~)Y;OS7~0Class-Student就这样构成了一个简单的一对多关系。当然在实际的项目中,也可以再建立一张Relation表来保存他们之间的关系,在这里为了简单,就不做Relation表了。51Testing软件测试网6vZ*X$}E
现在在项目中,我需要将Class表中的数据list显示,当然也想显示选择了这门课的Student的StuName。也可以说是将一对多关系转换为一对一关系。我所期望的显示格式是这样的:
NV4W J$Lv&B9CH0P \ iDYn FX0要做到这一点并不难,大体有两种思路:51Testing软件测试网]9v^){h#@q
1、在数据库中写一个函数
3U@3uE{(i02、在程序中获取表Class与表Student所有数据,然后对比ClassID51Testing软件测试网$Gm3z`%]
那么,那种方法效率比较高呢?于是我写了下面的代码来进行一个简单的测试
m'h _2x(R/\8^"WO)j0H q tk)A&d!rO RA0View Code
] oMHE_&bm051Testing软件测试网^Jf3k4[%kn51Testing软件测试网2Le0~[Cr-jg
class Program51Testing软件测试网VA@9gEH
{
gAh/s[l0 static void Main(string[] args)
W3g!Um!j'V(C.}0 {51Testing软件测试网+\3F.T5zd
_)[D
Sql sql = new Sql();51Testing软件测试网 Wn V4M?Z&}E
Stopwatch time1 = new Stopwatch();
~i^|tY1uD*m0 Stopwatch time2 = new Stopwatch();51Testing软件测试网YHU)jCU G
for (int j = 0; j < 10; j++)51Testing软件测试网jEx[A*siz[
{
Kcw$H0Z$_K0 time2.Start();51Testing软件测试网+x tAC]&h6HT7a
for (int i = 0; i < 1000; i++)
/kn([9|.?T,zHo0 {
#u JK5u8r:l0 string sql1 = "select ID,[StuName],[ClassID] FROM [Student]";51Testing软件测试网([3O
t MY$sK9?
string sql2 = " SELECT ID,ClassName from Class";51Testing软件测试网2iD@S4O6E$\5N
List<string> item = new List<string>();
c(]+q\w
i.N*A0 string bl="";51Testing软件测试网_ DI%nVL
DataTable dt1 = sql.getData(sql1);51Testing软件测试网)d-xZz.w{5{3x
DataTable dt2 = sql.getData(sql2);51Testing软件测试网;m,\c$Ns
foreach (DataRow dtRow2 in dt2.Rows)51Testing软件测试网mV NK s/Qn3P
{51Testing软件测试网H0p ^6b(e
foreach (DataRow dtRow1 in dt1.Rows)51Testing软件测试网#o:wq+m+cRQ9u
{51Testing软件测试网'zL!b/~XK({
if (dtRow1["ClassID"].ToString() == dtRow2["ID"].ToString())
$I"J.C
|;F5L+a V0 {51Testing软件测试网2HNt)b\ssC\
bl+=dtRow1["StuName"].ToString()+",";
csp~!E:Rv i0 }
#g2M4h#]3n[%i*j0 }
4]U#x^(MK'G0 item.Add(bl);51Testing软件测试网 q0YF'T'O
bl = "";51Testing软件测试网(^#]1f+zl
@D
}51Testing软件测试网1_bWB1m
}51Testing软件测试网/qN_0j-PY [f-f
time2.Stop();
4G\o6M)]Tk,V!z6H0 Console.WriteLine(time2.Elapsed.ToString());51Testing软件测试网#RpE9eh:G-z
uJq?2g+H \I,a0 time1.Start();51Testing软件测试网j6})Q^l z$O
for (int i = 0; i < 1000; i++)
(j}%p]4w [%Nu0 {
@_k*Ze t0 string sql3 = "SELECT C.ID, C.ClassName, dbo.f_getStuNamesByClassID(C.ID)as stuName FROM Class C";51Testing软件测试网8rxH4Ml_*c+B2c
DataTable dt = sql.getData(sql3);51Testing软件测试网3_k0\U9_-wnAt
}51Testing软件测试网/c7VO+x:U,Ch
time1.Stop();
"Ife9j4o)Pj9J0 Console.WriteLine(time1.Elapsed.ToString());51Testing软件测试网{?1dn/N)I5B]r
51Testing软件测试网E bn~hH
float index = (float)time1.Elapsed.Ticks / (float)time2.Elapsed.Ticks;
T
I"vn[ G2m'i1v1E0 Console.WriteLine("效率比" + index.ToString());51Testing软件测试网0Q|w8kG
_?;b0x
Console.WriteLine("=============================");
a;~V0EX7dS(_+K0 }
Console.ReadLine();