注:根据俺的工作经验,sql查询中带in的条件不少,特别是涉及多表或复杂查询时用的更多。
--sql中带in条件的查询及提高效率 ALTER PROCEDURE [dbo].[example1] ( @booker varchar(100) ) AS declare @str varchar(1000) set @str='select * from tb_itregister where booker in(' + @booker + ')' execute (@str) ----调用: string booker = "a,b"; booker = booker.Replace(",", "','"); booker = "'" + booker + "'"; /************************************************************ 问题描述: id值可能有数千个之多,怎么提高效率? 例子:select * from table1 where id in (1,3,6,10,...,8000) and type = 1 ************************************************************/ --例如: SELECT * FROM tb WHERE id IN (1, 2, 3, 4, ........) AND NAME = 'best' --1.将括号的条件做成变量 DECLARE @str VARCHAR(4000) SET @str = '1,2,3,4,5.......' --2.然后将@s拆分后插入临时表 CREATE TABLE #t ( id VARCHAR(10) ) DECLARE @i INT DECLARE @len INT SET @i = 1 WHILE @i < LEN(@str + ',') BEGIN INSERT #t SELECT SUBSTRING(@str + ',', @i, CHARINDEX(',', @str + ',', @i) -@i) SET @i = CHARINDEX(',', @str + ',', @i) + 1 END --3利用临时表和原表进行连接取值 SELECT k.* FROM tb k INNER JOIN #t p ON p.id = k.id WHERE NAME = 'best'
原文链接:http://www.cnblogs.com/zengxiangzhan/archive/2010/01/03/1638152.html