使用场景
一个计算价格的函数,多个存储过程调用,因业务需求经常要新增参数,避免修改函数时程序执行存储过程报错,将多个参数拼接为一个字符串传递
- -- 调用函数
- CalcuPrice(UnitPrice,CONCAT('MFQZC=',MFQZC,'&ItemNum=',ItemNum,
- '&AssmCode=',AssmCode))
-
- -- 定义函数
- function [CalcuPrice](
- @UnitPrice decimal(38, 3), -- 单价
- @ARGS varchar(900)
- )
- returns decimal(38, 3)
- as begin
- /****************************************
- * 解析参数列
- ****************************************/
- -- 1、定义接受参数列表的变量
- declare @MFQZC varchar(100),
- @ItemNum varchar(100)/*物料编码*/,
- @AssmCode varchar(100)/*加工件编码*/
- declare @Str0 varchar(100),
- @Str1 varchar(100),
- @Str2 varchar(100)
- -- 2、循环读取键值对
- declare S_subject CURSOR FAST_FORWARD FOR
- select data from dbo.SplitStr(@ARGS,'&');
- open S_subject;
- fetch next from S_subject into @Str0;
- while @@FETCH_STATUS=0
- begin
- set @Str1= (select data from (select ROW_NUMBER() over (ORDER BY (select 1)) RowNum,data from dbo.SplitStr(@Str0, '=')) a where RowNum=1)
- set @Str2= (select data from (select ROW_NUMBER() over (ORDER BY (select 1)) RowNum,data from dbo.SplitStr(@Str0, '=')) a where RowNum=2)
- if(@Str1='MFQZC')
- begin
- set @MFQZC=@Str2
- end
- else if(@Str1='ItemNum')
- begin
- set @ItemNum=@Str2
- end
- else if(@Str1='AssmCode')
- begin
- set @AssmCode=@Str2
- end
- fetch next from S_subject into @Str0;
- end
- close S_subject;
- deallocate S_subject;
- end;
- -- 接下来就可以用从字符串中解析出来的参数进行后续逻辑处理