sql存储过程里substring()和charindex()的一点技巧用法

今天学习了一点SQL存储过程,拿出来和大家分享下,本人刚学不久,如有出入还请见谅。

比如做一个学生选课系统 数据库有3张表 students(ID,Name,Age) ,courses(ID,Name),selectedcourses(studentID,courseID)括号里是字段。

下面是存储过程 根据传来的学生姓名以及选课构成的字符串,保存数据

@name nvarchar(50),

@age int,
@text nvarchar(50),-- 比如@text='1|4|15|'

AS
begin
      declare @tmp nvarchar(50)
       declare @stuid int
       declare @i int
      declare @claID int
       set @tmp=@text;
       insert into students([name],age)values(@name,@age)
     set @stuid=@@identity   --得到新增学生ID
    while(len(@tmp)>0)-----判断剩余字符串长度是否大于0。
    begin
set @i=charindex('|',@tmp)      ---- @i=2
   set @claID=substring(@tmp,1,@i-1)
-----@claid=1
    insert into SelectClasses(studentID,classID)values(@stuid,@claID);
   set @tmp=substring(@tmp,@i+1,len(@tmp)-@i)   
---@temp='4|15|'
   end
end

这样就完成了学生选课。


posted @ 2011-02-27 21:32  部落小头目  阅读(2574)  评论(0编辑  收藏  举报