跳至正文

【数据库】存储过程Stored Procedure

标签:

在学习数据库和 ERP 底层的内容时,发现一个新概念——存储过程。借助于强大的 AI,可以先快速构建知识,从而获得几个关键点:

  • 存储结构是预先在数据库中编辑、存储好的 SQL 代码
  • 存储结构可以被外部调用,并实现输入、输出,因此实现了轻度编程,相当于特定自定义方法的封装

不过,从”存储过程”的英文来看,Stored Procedure翻译为“存储程式”或者“存储程序”更加准备,从而强调内部的可执行性。

Stored Procedure在 1999 年 SQL 版本中正式引入,距今也已经超过二十多年历史了。

了解详细信息:

1. runoob.com1. runoob.com2. wiki.mbalib.com

二、案例解析

基于上述的内容,我就可以ERP 底层的如下逻辑了。

首先,创建了一个名称为“IdGenerator”的可执行程序,它包含一个名称为seqNo的参数,并指定 bigint 为数据类型,它返回的数据类型也是 bigint。

其次,begin 到 end 部分指明了它的程序主体,返回从’2015-11-01’到当前时间戳current timestamp的毫秒间隔。

create function "monitor"."IdGenerator"( @seqNo bigint ) 
returns bigint
as
begin
  declare @value bigint
  select @value = ("DATEDIFF"("millisecond",'2015-11-01',current timestamp)/250)*1073741824+(@seqNo&1073741823)
  return @value
end de

可见,monitor ERP 中应该用这个来生成程序内部全局唯一编码。用这个结果来作为主键,就能保证任何表之间的主键都是唯一的了。

还可以看一下更加复杂一点的,使用两个参数,返回某个日期所在周的第一天。

create function "monitor"."GetFirstDayOfWeek"( @date "DATETIME",@weekStartDay integer ) 
returns "datetime" /*
Find the first date on or before @DATE that matches 
day of week of @weekStartDay.
*/
as
begin
  declare @StartOfWeekDate "datetime"
  declare @FIRST_BOW "datetime"
  -- Check for valid day of week
  if @weekStartDay between 1 and 7
    begin
      -- Find first day on or after 1900-01-01
      -- matching day of week of @weekStartDay
      select @FIRST_BOW = "ymd"(1900,1,1+("remainder"((@weekStartDay+5),7)))
      -- Verify beginning of week not before 1900-01-01
      if @DATE >= @FIRST_BOW
        begin
          select @StartOfWeekDate = "dateadd"("dd",("datediff"("dd",@FIRST_BOW,@DATE)/7)*7,@FIRST_BOW)
        end
    end
  return @StartOfWeekDate
end 

上述考虑了一周从周一或是周二开始这样的特殊性。

参考:

SQL 标准 http://standards.iso.org/ittf/PubliclyAvailableStandards/index.html


了解 喜乐君 的更多信息

订阅后即可通过电子邮件收到最新文章。