现在的位置: 首页 > 综合 > 正文

黑马程序员_学习日记51_621数据库开发及ADO.Net(游标、动态sql)

2013年12月13日 ⁄ 综合 ⁄ 共 2099字 ⁄ 字号 评论关闭

SqlHelper报异常

类型初始值引发异常说明SqlHelper类中的字段属性设置错误

 

游标

使用步骤

--1、定义游标

declare
cur_MyStudent
cursor
fast_forward
for
select
* from
MyStudent

--2、打开游标

open cur_MyStudent

--2.1对游标的操作

--将每条数据读取并输出

--2.1.1将游标向后移动一条

fetch next
from cur_MyStudent

--将游标循环向后移动,直到末尾

while
@@fetch_Status
=0

begin

    fetch
next
from cur_MyStudent

end

--3、关闭游标

close cur_MyStudent

--4、释放资源

deallocate
cur_MyStudent

举例

1查询TblTeacher表中的数据为每个老师增加工资每个老师的工资增长数额不同具体增加额度在TblTeacherSalary表中

--(1)创建TblTeacherSalary的游标

declare
cur_TblTeacherSalary
cursor
forward_only

for --获取每行的teacherId,以及要增加的工资reward

select tTId,reward
from TblTeacherSalary

 

declare
@teachId
int

declare
@treward
money

open cur_TblTeacherSalary

 

fetch next
from cur_TblTeacherSalary
into @teachId,@treward

 

while
@@fetch_status
=0

begin

    --执行update …set salary=…Where id=@id

    update
TblTeacher
set tTSalary=tTSalary+@treward
where ttid=@teachId

    fetch
next
from cur_TblTeacherSalary
into @teachId,@treward

end

close cur_TblTeacherSalary

deallocate
cur_TblTeacherSalary

2现在要更新TblTeacherSalary让每个老师的奖金为老师原来的工资*0.3再加上现在表中的值

declare
@tid
int

declare
@salary
money

--定义游标,从TblTeacherSalary中查ttid

declare
cur_reward
cursor
forward_only
for
select
ttid from
TblTeacherSalary

 

open cur_reward

fetch next
from cur_reward
into
@tid

while
@@fetch_status
=0

begin

    --根据@tid查询当前员工的工资

    set
@salary
=(select
ttsalary from
TblTeacher
where
ttid
=@tid)

    --更新奖金表(更新的是游标当中当前正在循环的这条记录)

    update
cur_reward
set reward=reward+@salary*0.3
where current
of
cur_reward

    fetch
next
from cur_reward
into @tid

end

 

close cur_reward

deallocate
cur_reward

 

参数

//参数一般用在where语句后或者赋值时select
@count=...
from

//不能把表名列名等用参数来代替

//比如select
@col1,@col2
from @table1

string sql
= "select count(*) from @tbName";

SqlParameter
p1
= new
SqlParameter
("@tbName","TblStudent");

 

动态sql

--使用动态Sql非常灵活,但不可避免注入攻击

--通过各种手段只能减小危害,不能完全避免

--比如:

declare
@sql
nvarchar(1000)

declare
@tbname
nvarchar(11)

set @tbname
= 'TblStudent;select * from sysobjects;;exec sp_databases;drop database bbs'

set @sql
= 'select * from';

set @sql
= @sql
+
@tbname

exec(@sql)

 

declare
@sql
nvarchar(500)

--#rdCount是局部临时表,##开头是全局临时表

create table
#rdCount(rsCount
int)

--完全是错误的,这里只会把@count变量作为一个sql语句的字符串来拼接

set @sql='declare @count int;select @count=count(*) from TblStudent;insert into #rdCount values(@count);'

exec(@sql)

抱歉!评论已关闭.