试图找到喜欢和不喜欢的替代品(SQL)

时间:2013-06-05 13:15:10

标签: sql sql-server-2008

SELECT.....

 (v1.PCG like 'n0%'
or
v1.PCG like 'n1%'
or
v1.PCG like 'n2%'
or
v1.PCG like 'n3%'
or
v1.PCG like 'n4%'
or
v1.PCG like 'n5%'
or v1.PCG='N63Af1')

and v1.PCG not like 'N2D%'
and v1.PCG not like 'N2E%'
and v1.PCG not like 'N2C%'
and v1.PCG not like 'N2F%'
and v1.PCG not like 'N2J%'
and v1.PCG not like 'N2K%'
and v1.PCG not like 'N2U%'
and v1.PCG not like 'N2GC%'
and v1.PCG not like 'N2GD%'
and v1.PCG not like 'N2GH%'
and v1.PCG not like 'N2GJ%'
and v1.PCG not like 'N2GK%'
) as 'Value Of PN Orders',

from........

我已经完成了我的代码,但我正在尝试找到一种更有效的方式来做这件事,我看了一下但却找不到另一种方法......有什么建议吗?

4 个答案:

答案 0 :(得分:4)

Like支持字符类;

where v1.PCG like 'n[12345]%'

答案 1 :(得分:2)

这个特殊情况可以使用通配符 - 不需要正则表达式:

(v1.PCG LIKE 'n[0-5]%' OR v1.PCG='N63Af1')
AND v1.PCG NOT LIKE 'N2[CDEFJKU]%'
AND v1.PCG NOT LIKE 'N2G[CDHJK]%'

一个不会改变语义但是会读得更清晰的替代方法是使用表变量或CTE来加入:

 DECLARE @match TABLE (Value varchar(5))
 INSERT @match VALUES 
    ('N0%'),
    ('N1%'),
    ('N2%'),
    ('N3%'),
    ('N4%'),
    ('N5%'),
    ('N63Af1')

 DECLARE @not TABLE (Value varchar(5))
 INSERT @not VALUES 
    ('N2D%'),
    ('N2E%'),
    ('N2C%'),
    ('N2F%'),
    ('N2J%'),
    ('N2K%'),
    ('N2U%'),
    ('N2GC%'),
    ('N2GD%'),
    ('N2GH%'),
    ('N2GJ%'),
    ('N2GK%')

SELECT ...
JOIN @match ON
     v1.PCG LIKE @match.Value
LEFT OUTER JOIN @not ON
     v1.PCG NOT LIKE @not.Value
WHERE
     @not.Value IS NULL

如果您的值是用户提供的,这是一个很好的技巧。但是,在这种情况下,我认为通配符集赢了以方便使用。

答案 2 :(得分:0)

这似乎是 regular expressions

的工作

答案 3 :(得分:0)

您可以在T-SQL查询的WHERE CLAUSE中使用CONTAINS()谓词。

SELECT <<COLUMNS>>
FROM   <<TABLE>>
WHERE CONTAINS(<<COLUMN TO SEARCH>>, <<VALUE TO SEARCH>>);

进一步阅读: MSDN : CONTAINS (T-SQL)