0

我有一个表值参数(@KEYWORD),它只有一列,其中包含 0 到多行关键字,这些关键字将针对一两个数据库 (nvarchar) 列(REMARKS 和 SUPPLEMENTAL_REMARKS)进行查询。超级简单的概念。

我遇到的问题是如何编写 SQL 来检查针对一个(或两个)数据库列提供的每个单独的关键字。

这是我未完成的 WHERE 子句部分......

WHERE
(
    CASE WHEN EXISTS (SELECT 1 FROM @KEYWORD) THEN
        --check that some combination of either REMARKS or SUPPLEMENTAL_REMARKS contains all supplied values
        CASE WHEN (
        --  RES.REMARKS (or RES.SUPPLEMENTAL_REMARKS) LIKE %keyword[0]%
        --  AND
        --  RES.REMARKS (or RES.SUPPLEMENTAL_REMARKS) LIKE %keyword[1]%
        --  AND
        --  ... (this doesn't work for many reasons, but is just to give an idea)
        ) THEN
            1
        ELSE
            0
        END
    ELSE --TVP (@KEYWORD) not supplied, so ignore this filter
        1
    END
) = 1
4

2 回答 2

1

可以使用 JOIN 吗?然后 DISTINCT 仅返回到源表,因此当您匹配多个关键字时不会得到多行。

select distinct res.*
from sourcetable res 
join @keywords kw on res.REMARKS like '%'+kw.keyword+'%' or res.SUPPLEMENTAL_REMARKS like '%'+kw.keyword+'%'

如果您需要全部匹配并在关键字为空时仅显示所有源行

select res.id, res.REMARKS, res.SUPPLEMENTAL_REMARKS from (
  select res.id, res.REMARKS, res.SUPPLEMENTAL_REMARKS
  from sourcetable res
  join @keywords kw on res.REMARKS like '%'+kw.keyword+'%' or res.SUPPLEMENTAL_REMARKS like '%'+kw.keyword+'%'
  group by res.id, res.REMARKS, res.SUPPLEMENTAL_REMARKS
  having count(*) = (select count(*) from @keywords)
) k1 UNION ALL SELECT res.id, res.REMARKS, res.SUPPLEMENTAL_REMARKS FROM (
  SELECT * WHERE 0=(select count(*) from @keywords)
) k0
于 2013-01-08T23:30:17.523 回答
1

根据下面的 SQL 注释,您只需要来自 res 的记录,其中所有关键字都与 REMARKS 或 SUPPLEMENTAL_REMARKS 匹配。

 --  REMARKS (or SUPPLEMENTAL_REMARKS) LIKE %keyword[0]%
        --  AND
        --  REMARKS (or SUPPLEMENTAL_REMARKS) LIKE %keyword[1]%
        --  AND
        --  ... (this doesn't work for many reasons, but is just to give an idea)

最简单的方法是加入并进行计数并确保它与 @KEYWORD 中的关键字数量相匹配

DECLARE @KEYWORDCOUNT as INT
SELECT @KEYWORDCOUNT = COUNT(*) FROM @Keyword

SELECT ID, [REMARKS], [SUPPLEMENTAL_REMARKS]
FROM 
  res r
  INNER JOIN @Keyword k
  ON r.REMARKS like '%' + k.keyword + '%'
     OR r.SUPPLEMENTAL_REMARKS like '%' + k.keyword + '%'


GROUP BY 
  ID,[REMARKS], [SUPPLEMENTAL_REMARKS]
HAVING COUNT(ID) = @KEYWORDCOUNT

一种让它进入你的地方的方法是这样的

WHERE
  @KEYWORDCOUNT = 0 
  OR 
  res.id in (SELECT ID
            FROM 
                res r
                INNER JOIN @Keyword k
               ON r.REMARKS like '%' + k.keyword + '%'
                 OR r.SUPPLEMENTAL_REMARKS like '%' + k.keyword + '%'
             GROUP BY 
              ID
             HAVING COUNT(ID) = @KEYWORDCOUNT)

您可能需要考虑将 @KEYWORDCOUNT 作为参数传递,因为 DataTable.Rows.Count 几乎是免费的

演示

于 2013-01-08T23:38:23.687 回答