SQL 创建存储过程,让主键自增

1、  首先创建存储过程;

2、  然后分别创建序列,生成基金公司编号、基金代码、活期账号、理财账号、基金账户、合同号。要求如下:

  • 基金公司编号,字母K+5位数字。
  • 基金代码,字母V+6位数字。
  • 活期账号,13位数字。
  • 理财账号,13位数字。
  • 基金账户,字母L+5位数字。
  • 合同号,字母Z+6位数字。

3、 在创建存储过程中,在添加表数据的时候,自动添加生成的主键编号。【存储过程添加数据】

 1 use Funds
 2 go
 3 //创建存储过程:基金公司编号,字母K+5位数字
 4 --   基金公司编号,字母K+5位数字。
 5 alter proc Proc_Create_FundCompanyID
 6       @ID  varchar(30) out  ---定义为输出参数
 7 as
 8     begin
 9         declare @num int
10         select top 1 @ID=[CompanyId] from [dbo].[FundCompany] order by [CompanyId] desc
11         --判断数据库中是否含有数据
12         if(@ID is null)
13             begin
14                 set @ID='K00001' 
15             end
16         else
17             begin
18                 -- 截取数字部分
19                 Set @ID =right(@ID,5)  ---00009
20                 -- 把字符型的数字转换为整型
21                 set @num = CONVERT(int,@ID)   ---9
22 
23                 set @num =@num +1;
24                 --拼接 0000  补齐右边的位数 10
25                 set @ID = '0000'+convert(varchar(20), @num)
26                 select @ID
27 
28                 Set @ID =right(@ID,5) 
29                 set @ID='K'+@ID
30             end
31     end
32     
33 go        
34 
35 -- 调用存储过程
36 
37 declare @companyId varchar(30)
38 exec  Proc_Create_FundCompanyID @companyId out
39 select @companyId
40 
41 //创建活期账号,13位数字。
42 --活期账号,13位数字。
43 ---2017-08-25 14:46:45 毫秒数
44 
45 alter proc  Proc_Create_CurrentAccount
46   @Account nvarchar(20) out
47   as
48     begin
49     declare  @str nvarchar(50)
50         Set  @str = CONVERT(nvarchar(50),getdate(),126)
51         set  @str = REPLACE(@str,'-','')
52         set  @str = REPLACE(@str,'T','')
53         set  @str = REPLACE(@str,':','')
54         set  @str = REPLACE(@str,'.','')
55         set @Account =left(@str,1)+RIGHT(@str,12)
56     end
57 go
58 
59 declare @account nvarchar(20)
60 exec Proc_Create_CurrentAccount @account out
61 select @account

68 //向表中添加数据 69 create proc Proc_Insert_FundCompany 70 @Name nvarchar(30), 71 @Content nvarchar(500), 72 @Money money, 73 @State bit 74 as 75 begin 76 declare @companyId varchar(30) 77 exec Proc_Create_FundCompanyID @companyId out 78 insert into [dbo].[FundCompany] values(@companyId,@Name,@Content,@Money,@State) 79 end 80 go 81 82 83 exec Proc_Insert_FundCompany '呵呵100','哎呦喂',500,0 84 85 select * from [dbo].[FundCompany] 86 87 88 89 create proc Proc_Insert_Fund 90 @CompanyId nvarchar(5) 91 as 92 begin 93 select 94 95 --insert into (插入数据) 96 end 97 98 go
原文地址:https://www.cnblogs.com/pang951189/p/7440967.html