朕写的在sql中循环

exec [GetListById] '1,2,3,4,5', ','

USE [Lib]
GO
/****** Object:  StoredProcedure [dbo].[GetListById]    Script Date: 12/26/2011 15:02:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: 

-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[GetListById]
 -- Add the parameters for the stored procedure here
 @idList nvarchar(1000) ,--字符窜
 @splitchar nvarchar(100)--拆分字符
AS
BEGIN
 
 declare @i int
 declare @ti int
 declare @sql nvarchar(1000)
 
set @sql=' select * from dbo.goods_products
   where (1=1) and ('
  
set @i=charindex(@splitchar,@idList)
   while @i>=1 --循环
   begin

 set @sql=@sql+'  id='+replace( substring(@idList,@i-1,@i),',','') +' or'
   set @idList=substring(@idList,@i+1,len(@idList)-@i)
   set @i=charindex(@splitchar,@idList)
   if(@i=0)
   begin
    set @sql=@sql+'  id='+replace( substring(@idList,0,@i+2),',','')
  print(@i) 
  end
   end
  
  set  @sql=@sql+')'
 print(@sql) 
 
END
 

原文地址:https://www.cnblogs.com/qq4004229/p/2302208.html