开发者

COALESCE together with FTS

I have a form that has a 'brand' dropdown and a 'model' dropdown.I am searching for cars here that has some brand and/or a model. Now if I choose "all" from the 'brand' dropdown and some 'model' value other then the "all" ,I use

COALESCE(@brand,cars.brand)

and

COALESCE(@model,cars.model)

, it works fine as in returning all the cars if I choose "all" for both the dropdown menus and specific results if I choose some value. Now I want to use FTS with the CONTAINS keyword and using a query like

CONTAINS(cars.model , 'COALESCE(@model,cars.model)')

is returning with an error as

Syntax error near '(' in the full-text search condition 'COALESCE(@model,cars.model)'.

I would really appreciate if someone can refer me to a query/sproc that is FTS together with COALESCE .Please help. P.S

SET @SQL = '
SET @query_result = ( 
    SELECT items.id AS "ID"
            ,items.title AS "Title"
            ,cars.brand AS "Brand"
            ,cars.model AS "Model"
            ,cars.type AS "Type"
            ,items.city AS "City"
            ,items.name AS "开发者_Go百科Name"
            ,items.date_added AS "Date"
            ,items.small_1 AS "Image"
      FROM [cars]
      JOIN [items] 
        ON items.id=cars.item_id
     WHERE cars.item_id = COALESCE(@item_id,cars.item_id)
            AND CONTAINS(cars.brand ,''COALESCE('+@brand+',cars.brand)'')
            AND cars.model = COALESCE(@model,cars.model)
            AND cars.type = COALESCE(@type,cars.type)
            AND items.city = COALESCE(@city,items.city)
            AND DATEDIFF(DAY,items.date_added,GETDATE())<=COALESCE(@period,items.date_added)
            AND items.new = COALESCE(@isnew,items.new)
       FOR XML
      PATH(''car''),ROOT(''items''))'


eThis is a pattern I've never seen before, so forgive me if I'm isunderstanding.

I'm pretty sure this line is the problem.

AND CONTAINS(cars.brand ,''COALESCE('+@brand+',cars.brand)'')

The problem with this is that it's going to generate the clause:

AND CONTAINS(cars.brand, 'COALESCE(toyota,cars.brand)')

I don't think that's a syntax error exactly, but that coalesce expression is a literal string at that point and the evaluation won't happen. You'll also have a problem if brand is null, because you'll be appending NULL to the first and last part of the SQL code.

You could try simply:

AND CONTAINS(cars.brand, coalesce(@brand, cars.brand))

without all the escaping. If for some reason that doesn't work, try:

' + CASE WHEN @brand is null then '' else 'AND CONTAINS(cars.brand, @brand)' end + '

This will only insert the clause when @brand is not null in the first place, and isn't subject to the sql injection vulnerability that it would be if you were manually escaping quotes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜