加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sqlserver 查找某个字符在字符串中第N次出现的位置

发布时间:2020-12-12 13:02:49 所属栏目:MsSql教程 来源:网络整理
导读:前几天的考试系统出现了一个问题,背景大概就是告诉你正确答案,比如说是:答案1#答案2#答案3...而几百个学生答题的记录也是这样格式存储的,问如何用sql语句为每个学生判分? 思路: 第一步:找到第N个#在字符串中的位置 create ? function ? fn_find(@find
前几天的考试系统出现了一个问题,背景大概就是告诉你正确答案,比如说是:答案1#答案2#答案3...而几百个学生答题的记录也是这样格式存储的,问如何用sql语句为每个学生判分?
思路:
第一步:找到第N个#在字符串中的位置
create
? function ? fn_find(@find? varchar (8000),@str? varchar (8000),@n? smallint ) ???? returns ? int as begin ???? if @n < 1? return ? (0) ???? declare ? @start? smallint ,@ count ? smallint ,@ index ? smallint ,@len? smallint ???? set ? @ index ? = charindex(@find,@str) ???? if @ index ? = 0? return ? (0) ???? else ? select ? @ count ? = 1,@len = len(@find) ???? while @ index ? > 0? and ? @ count ? < @n ???????? begin ???????????? set ? @start = @ index ? + @len ???????????? select ? @ index ? = charindex(@find,@str,@start),@ count ? = @ count ? + 1 ???????? end ???? if @ count ? < @n? set ? @ index ? = 0 ???? return ? (@ index ) end go 第二步: 截取学生第N道题的答案和正确答案第N道题做比较,把做对的人的分数加1。 update dbo.T_dxyysyj_BankedCloze2_Record set Fraction =Fraction +1 where QuestionID ='3' and SUBSTRING(ExamAnswer,dbo.fn_find(@find,@mystart)+1,@mylength)=SUBSTRING(@str,@mylength) 第三步: 封装成存储过程。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读