编写一个SQLSERVER 存储过程

一个STUDENT表 其中 姓名NAME(10) NO( 30) ID自动增量列(100,10) 要求SNAME中所有前2个字母为“WA"的SNO前加上前缀’cay_'编写一个含有输出参数@ID的存储过程

当执行该过程时能够返回当前STUDENT表最大ID字段的值 并在输出穿口打印找到的最大值 如果最大值小于100,则显示”没有找到“

代码是最好的文字,不多说,请看我的代码,并给分,呵呵。

--step1. 建表
if exists(select * from sysobjects where id=object_id('student') and objectproperty(id,'IsTable')=1)
drop table student
go
create table student
(
id int identity(100,10) not null
,sname varchar(10) not null
,sno varchar(30) not null
)
go

--step2.建存储过程
if exists(select * from sysobjects where id=object_id('proc_demo') and objectproperty(id,'IsProcedure')=1)
drop procedure proc_demo
go
create procedure proc_demo
@o_maxid int output
as
set nocount on

--如果希望大小写敏感,使用第一句,因为SQL Server默认是大小写不敏感的
--update student set sno='cay_'+sno where ascii(substring(sname,1,1))=87 and ascii(substring(sname,2,1))=65 and sno not like 'cay_%'
update student set sno='cay_'+sno where sname like 'WA%' and sno not like 'cay_%'

print convert(varchar(10),@@rowcount)+'条记录符合条件并被处理'

select @o_maxid=max(id) from student where id>=100
if(@o_maxid is null) print '没有找到符合条件的最大记录'

set nocount off
go

--测试数据1
truncate table student
set identity_insert student on
insert into student(id,sname,sno)values(1,'WA1','1');
insert into student(id,sname,sno)values(2,'wa2','2');
insert into student(id,sname,sno)values(3,'3','3');
set identity_insert student off
go

--测试数据2
truncate table student
insert into student(sname,sno)values('WA1','1');
insert into student(sname,sno)values('wa2','2');
insert into student(sname,sno)values('3','3');
go

--测试过程
declare @maxid int
exec proc_demo @maxid out
print '最大id是'+convert(varchar(10),@maxid)
go
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-06-28
很对