模糊SQL搜索

时间:2011-12-09 19:00:16

标签: sql sql-server

使用SQL Server 2005

给出一张表:

| Role  | Low  | High |
| A     | AA00 | ZZ*  |
| B     | *    |      |
| C     | AA00 | AZ99 |

如何执行选择值在LOW - HIGH范围内的行的查询。

e.g。如果我将“低”和“高”与“BB”进行比较,我想选择角色A和B,如果我将范围与'22'进行比较,我想选择角色B.

AB99应该返回A,B,C

1 个答案:

答案 0 :(得分:2)

试试这个:

DECLARE @CompVal VarChar(100) = '22';

WITH T AS (
  SELECT Role, Low, High
  FROM (
    SELECT 'A' Role, 'AA00' Low, 'ZZ*' High
    UNION
    SELECT 'B' Role, '*' Low, NULL High
    UNION
    SELECT 'C' Role, 'AA00' Low, 'AZ99' High
  ) U
)
SELECT *
FROM T
WHERE @CompVal BETWEEN Low AND High
  OR (@CompVal >= Low AND NULLIF(High, '*') IS NULL)
  OR (NULLIF(Low, '*') IS NULL AND @CompVal <= High)
;

我假设您的*NULL值都用作通配符值。这会为您的每个示例案例生成正确的结果。

请注意,这还取决于您使用的排序规则。对于大多数人(包括默认排序规则SQL_Latin1_General_CP1_CI_AS),它会很好。

编辑:仔细观察,您可能希望将WHERE子句替换为:

WHERE @CompVal BETWEEN
      REPLACE(ISNULL(Low, '*'), '*', '0000')
  AND REPLACE(ISNULL(High, '*'), '*', 'ZZZZ')