您的位置:首页 > 职场人生

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

2012-06-23 17:23 615 查看
一、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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐