1、存储过程中,使用in查询时的参数处理方式
使用情形描述:传入存储过程的参数为一个字符串@IDs,以固定分隔符连接
新建字符串分割函数,然后将分割结果传入存储过程:
CREATE FUNCTION [dbo].[Split] ( @c VARCHAR(MAX) , @split VARCHAR(50) ) RETURNS @t TABLE ( col VARCHAR(50) ) 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 * from table where id In (select * from Split(@ids , ‘,‘))
2、SQL2005及以上版本,使用with语法查询树形结构
WITH tempData(id,pid,name) as (
select id,pid,name from roleTable where roleID = 8
AND
UNION ALL
select id,pid,name from roleTable r1 INNER JOIN tempData r2 on r1.pid = r2.id
)
select id,pid,name from tempData where …………
)