CONTAINS中的case语句的语法错误

时间:2015-02-05 14:55:55

标签: sql sql-server tsql ssms

select  Rowid, @counter
from Patients where 
Contains
((case when @ColumnnName = 'firstname' then firstname  --here
            when @ColumnnName = 'middlename' then middlename 
            when @ColumnnName = 'lastname' then lastname 
           end), SUBSTRING(@parameterFromUser, 1, @counter));   --here

我在casethen@parameterFromUser收到语法错误。语法似乎有什么问题? SSMS在这些单词上显示红色

2 个答案:

答案 0 :(得分:2)

您可以将其写为包含多个where的单个contains

select Rowid, @counter
from Patients
where (@ColumnnName = 'firstname' and Contains(firstname, SUBSTRING(@parameterFromUser, 1, @counter)) ) or
      (@ColumnnName = 'middlename' and Contains(middlename, SUBSTRING(@parameterFromUser, 1, @counter)) ) or
      (@ColumnnName = 'lastname' and Contains(lastname, SUBSTRING(@parameterFromUser, 1, @counter)) );

作为备注:我不确定这将如何优化。

我可能会建议使用子查询方法:

select *
from (select Rowid, @counter
      from Patients
      where Contains((firstname, middlename, lastname ), SUBSTRING(@parameterFromUser, 1, @counter)) 
     )
where @ColumnName = 'firstname' and firstname like '%' + @parameterFromUser + '%' or
      @ColumnName = 'middlename' and middlename like '%' + @parameterFromUser + '%' or
      . . .

这不完全匹配。它假定contains()将大大减少被搜索的行数。但是,它具有一定的优势,例如,如果需要,可以轻松搜索多列。

答案 1 :(得分:1)

语法错误。你不能这样做。

CONTAINS ( 
     { 
        column_name | ( column_list ) 
      | * 
      | PROPERTY ( { column_name }, 'property_name' )  
     } 
     , '<contains_search_condition>'
     [ , LANGUAGE language_term ]
   ) 

您可以使用一列或(列列表)。

您可以重写为:

If @ColumnnName = 'firstname'
    Insert into @ResultTable(...Columns...)
    select  Rowid, @counter
    from Patients where 
    Contains(firstname, SUBSTRING(@parameterFromUser, 1, @counter));  
Else IF If @ColumnnName = 'middlename'
    Insert into @ResultTable(...Columns...)
    select  Rowid, @counter
    from Patients where 
    Contains(middlename, SUBSTRING(@parameterFromUser, 1, @counter)); 

实际上你也不能使用SUBSTRING(@parameterFromUser, 1, @counter)。你应该为此声明单独的变量。