欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL实现递归及存储过程中In()参数传递解决方案详解

程序员文章站 2023-12-05 08:20:10
1.sql递归 在sql server中,我们可以利用表表达式来实现递归算法,一般用于阻止机构的加载及相关性处理。 -->实现: 假设organiseunit(...

1.sql递归

在sql server中,我们可以利用表表达式来实现递归算法,一般用于阻止机构的加载及相关性处理。

-->实现:

假设organiseunit(组织机构表)中主要的三个字段为organiseunitid(组织机构主键id)、parentorganiseunitid(组织机构父id)、organisename(组织机构名称)

复制代码 代码如下:

with organise as
(select * from organiseunit where organiseunit.organiseunitid = @organiseunitid
union all select organiseunit.* from organise, organiseunit
where organise.organiseunitid = organiseunit.parentorganiseunitid)

select organisename from organise


上述sql语句实现了, 传入组织机构主键id,查询出其对应组织机构名称和其 全部下级组织机构名称。

2.存储过程中 in 参数传递

-->情景

① 通过刚才的sql递归方式,我们已经可以将一个组织机构和其全部下级单位查询出来;假设每个组织机构还有一个字段为organisecode(组织机构代码);

② 当我们需要按照组织机构代码进行筛选数据时,我们会用到 in 这个查询条件,例如select * from organiseunit where organisecode in ('10000001','10000003','10000002')

③但是in()中条件不可能总是固定不变的,有时我们需要用参数传递进去;我们可能会想到设定一个变量参数@organisecode,然后按照'10000001','10000003','10000002'的格式拼参数不就行了吗 ?

④in使用参数时会强制转换参数类型与条件字段一致,不支持构造字符串(如果字段本身为varchar、char型,则in相当于只有一个条件值,而不是一组)

-->实现

①可以使用exec,把整个sql当做参数来执行,例如:exec ('select * from organiseunit where organisecode in ('+@organisecode+')');这样存储过程修改复杂,没有防注功能。

②我们采用另一种方案来解决,先写一个sql函数,功能是分割字符串

复制代码 代码如下:

create  function  splitin(@c   varchar(2000),@split   varchar(2))  
returns   @t   table(col   varchar(20))  
as  
begin   
  while(charindex(@split,@c)<>0)  
    begin  
      insert   @t(col)   values   (substring(@c,1,charindex(@split,@c)-1))  
      set   @c   =   stuff(@c,1,charindex(@split,@c),'')  
    end  
  insert   @t(col)   values   (@c)  
  return  
end 

我们为这个函数传入字符串和分隔符,他就能将字符串按指定符号分割并作为查询结果返回。

例如:执行select col from splitin('10000001,10000002,10000003',',')

返回:

10000001

10000002

10000003

③有了这个函数,我们就有了新的解决方案了

定义参数@organisecode,为其传入字符串,这个参数由一个或多个organisecode构成,中间用“,”分割;

调用方式:select * from organiseunit where organisecode in (select col from splitin(@organisecode,','))