zoukankan      html  css  js  c++  java
  • [SQL]根据刚刚插入数据的 ID 向另外一张表插入数据(插入的其他字段数据需要对字符串进行分析)

    比如做一个学生选课系统 数据库有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
    这样就完成了学生选课。
  • 相关阅读:
    站立会议第四天
    站立会议第三天
    站立会议第二天
    站立会议第一天
    团队项目估算
    团队计划会议
    《人月神话》阅读笔记01
    《构建之法》阅读笔记06
    微软买书问题
    找水王2
  • 原文地址:https://www.cnblogs.com/beeone/p/3642079.html
Copyright © 2011-2022 走看看