• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

MySql存储过程的问题_MySQL

mysql 搞代码 4年前 (2022-01-09) 20次浏览 已收录 0个评论

gaodaima.com 以前没用过MySQL存储过程,第一次写有很多的不习惯,记录如下: 下面是一个最简单的MySQL存储过程,实现两个数相加,需要本文来源gaodai$ma#com搞$$代**码)网8特别注意的是
Sql代码 delimiter $$ create procedure proc_add(in a int,in b int) begin declare c int; if a is null then set a = 0; end if; if b is null then set b = 0; end if; set c = a + b; select c; end$$ delimiter ; 1. declare语句只能放在存储过程的开始位置,放在后面就会报错 2. if 语句的后面必须有then,但是不需要begin,在if结束时需要end if 3. 判断是否为NULL倒是和MSSQL一样都有IS NULL 4. delimiter是定界符的意思在结束的end后面要添加定界符 5. end if之后必须跟分号,否则语法错误 下面是一个较常见的场景,判断表中某列是否存在某值,如果存在执行某操作
Sql代码 delimiter $$ create procedure proc_add_book(in $bookName varchar(200),in $price float) begin declare $existsFlag int default 0; select bookId into $existsFlag from book where bookName = $bookName limit 1; if bookId > 0 then #if not exists (select * from book where bookNumber = $bookName) then insert into book(bookNumber,price) values($bookName,$price); end if; end$$ delimiter ; 需要注意的是不能用if exists;exists可以在where后面或者在create object是使用,但是在if语句中不可以使用,只能用变通的方法。 while语句也需要注意,下面是一个while的简单应用:
Sql代码 delimiter $$ create procedure proc_add_books_looply(in $bookName varchar(200),in $price float,in $insertTimes INT) begin while $insertTimes>0 do insert into book (bookName,price) values($bookName,$price); end while; end$$ delimiter ; 可以看到while后面跟条件,条件后面要跟一个do,在while循环体结束之后需要end while并以分号结束。 以上是一些简单的总结,希望有用。 作者 yukaizhao gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:MySql存储过程的问题_MySQL
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址