存储过程学习(一)

在学《数据库》这门课的时候老师讲“过存储过程”这东西,但一直没有自己写过,语法也不熟。现在公司要升级ERP系统了,这任务落在了我一个人身上。前一段时间改写了一部分程序功能但数据库的操作一直都采用在代码中拼接SQL的方式。后来在网上看到说这种方式容易被注入,而且在处理大量数据时效率很低,所以正考虑将之前的操作全部换成存储过程。

这次要处理的表比较简单:

存储过程学习(一)

表名 atr_win_m

主要想实现的功能为:

1.根据id_win_b和clm_filed字段查询是否有相应记录

2.有则更新,无则插入

3.插入时要调用另一个已经写好的存储过程pr_amt_max_no来生成ID号

4.插入完成后要调用存储过程pr_amt_max_update 更新表atm_max_no中相应的字段值

为简单起见,这里就不列出表atm_max_no和上面两个已经写好的存储过程的详细内容了。

----------------------------------------------------------------------------------------------

遇到了问题:pr_amt_max_no,和pr_amt_max_update这两个存储过程都是用select返回的结果集(虽然里面只包含两三个字段),网上有资料说一个存储过程中不能访问另一个存储过程产生的结果集。

----------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------

解决: 看来是不能在这个存储过程中直接进行判断并调用上面两个存储过程了,所以功能做了下修改:

根据id_win_b 和clm_filed字段查询是否有相应记录,有则更新并返回0,无则返回1。然后在CS代码中具体去处理。

存储过程如下:

/*说明: 本存储过程用于更新表 art_win_m 此过程先根据参数win_id,filedstr中的filedname 查询是否有相应记录,有则更新并返回0无则返回1 filedstr内容 : "clm_filed,clm_cap,clm_order,clm_width,clm_vis,clm_input" */ CREATE PROCEDURE [dbo].[pr_atr_win_m_update] @win_id char (10), --窗口ID号 @id_win_m char(10), --新建的记录的ID @username char(10), --当前用户名 @userdate datetime , --时间 @filedstr varchar(200) --含有字段信息的字符串格式为"a,b,c,d" AS declare @positiona int --指针1 declare @positionb int --指针2 declare @countno int --查询出的记录数 declare @filedname varchar(20) --存放取得的字段名 declare @ccaption varchar(20) --显示名称 declare @corder int --列顺序 declare @cwidth int --列宽 declare @cvis bit --是否可见 declare @cinput varchar(20) --数据显示格式如99,999.99 set @positiona = 0 set @positionb = 0 set @countno = 0 set @countno = 0 begin transaction set @positiona=CharIndex(',',@filedstr) --取得第一个豆号的位置 set @filedname=SubString(@filedstr,@positionb+1,@[email protected]) --取得字段名字符串,pa在前 set @positionb=CharIndex(',',@filedstr,@positiona+1) --第二个豆号位置 set @ccaption =SubString(@filedstr,@positiona+1,@[email protected]) --得显示名,pb在前 set @positiona=CharIndex(',',@filedstr,@positionb+1) --第三个豆号位置 set @corder=cast (SubString(@filedstr,@positionb+1,@[email protected]) as int) --得顺序号,pa在前 set @positionb=CharIndex(',',@filedstr,@positiona+1) --第四个豆号位置 set @cwidth=cast (SubString(@filedstr,@positiona+1,@[email protected]) as int) --得宽度,pb在前 set @positiona=CharIndex(',',@filedstr,@positionb+1) --第五个豆号位置 set @cvis=cast (SubString(@filedstr,@positionb+1,@[email protected]) as bit) --得显示,pa在前 set @cinput=SubString(@filedstr,@positionb+1,len(@filedstr)) --得显示格式 select @countno= count(*) from atr_win_m where id_win_b [email protected]_id and [email protected] if(@countno!=0) --有记录.也许用@countno==1判断更为合适? begin update art_win_m set [email protected], [email protected] ,[email protected], [email protected],[email protected],[email protected],[email protected],[email protected] return(0) end else return (1) GO