将过滤器值吐入条件sql

时间:2017-11-27 07:29:26

标签: sql sql-server sql-server-2008

我在函数中有一个过滤器和条件,它只适用于一个条件

我:e&#39; =&#39;     我希望它适用于所有条件,例如' IN'' >=''<='

这是代码

declare @filter VARCHAR(1000)  
    DECLARE @TempFilter VARCHAR(1000)  
    declare @Condition VARCHAR(1000)  
    set @Condition='Blocked'  
    SET @Filter=N'Blocked=0 and TYPE = 2 and ID = 1635729'  
    SET @Condition=@Condition+'='  
    SELECT   

    @TempFilter=SUBSTRING(@Filter,CHARINDEX(@Condition,@Filter),LEN(@Filter))  
    IF CHARINDEX('and',@TempFilter)=0  
    BEGIN  
    SET @Filter=SUBSTRING(@Filter,CHARINDEX(@Condition,@Filter)+LEN(@Condition),  
    LEN(@Filter)-LEN(@Condition)-LEN(@TempFilter))  
    END  
    ELSE  
    BEGIN  
    SET @Filter=SUBSTRING(@Filter,CHARINDEX(@Condition,@Filter)+LEN(@Condition),  
    CHARINDEX(' ',@TempFilter)-LEN(@Condition))  
    END  

请帮忙或建议。

1 个答案:

答案 0 :(得分:0)

您可以测试此代码吗

DECLARE @tempFilter VARCHAR(1000)  
declare @condition VARCHAR(1000)  
declare @filter VARCHAR(1000)
declare @operator VARCHAR(1000)
declare @trimmedFilter VARCHAR(1000)
set @Condition='Blocked'  
SET @filter=N'Blocked IN(0) and TYPE > = 2 and ID IN (1635729,15454)'  


WHILE LEN(@Filter) > 0
BEGIN
   IF CHARINDEX(' and',@filter)<> 0
   begin
   SET @TempFilter = RIGHT ( @filter , LEN(@filter) - CHARINDEX(' and',@filter)-4)
   SET @filter = LEFT ( @filter , CHARINDEX(' and',@filter))
   end
   SET @trimmedFilter =  REPLACE(@filter,' ','')
   set @operator =
   case
   when CHARINDEX('NOTIN(',@trimmedFilter) <> 0 then 'NOTIN' 
   when CHARINDEX('IN(',@trimmedFilter) <> 0 then 'IN'
   when CHARINDEX('>=',@trimmedFilter) <> 0  then '>='
   when CHARINDEX('<=',@trimmedFilter) <> 0 then '<='
   else '='
   end
   IF CHARINDEX(@Condition,@filter) <> 0
   BEGIN
      SET @filter = REPLACE(RIGHT(@trimmedFilter,LEN(@trimmedFilter) - CHARINDEX(@operator,@trimmedFilter)+1), 'NOTIN', 'NOT IN')
      BREAK
   END
   ELSE
   BEGIN
      SET @filter = @TempFilter         
      CONTINUE
   END
END