SQL Server通配符长度

时间:2019-06-12 00:14:42

标签: sql-server

我知道%将匹配一个或多个字符,而_将仅匹配一个字符。有没有办法让通配符匹配5个或更少的字符?我可以编写搜索1、2,..,5个字符的代码,但这太多了。

这是一个例子

Select *
From MyTable
Where MyTable.[Content] like 'mystring%myotherstring'

如果要用5或4或3或2或1个字符分隔“ mystring”和“ myotherstring”,我希望%匹配。大于5的任何间隔将不匹配。

谢谢!

2 个答案:

答案 0 :(得分:4)

您可以使用单字符通配符_

SELECT *
FROM MyTable
WHERE
    Content LIKE 'mystring_myotherstring' OR
    Content LIKE 'mystring__myotherstring' OR
    Content LIKE 'mystring___myotherstring' OR
    Content LIKE 'mystring____myotherstring' OR
    Content LIKE 'mystring_____myotherstring';

请注意,SQL Server的增强型LIKE运算符不支持可变宽度通配符。另外,也许您想将%放在LIKE表达式的两端,例如

WHERE Content LIKE '%mystring_myotherstring%'

答案 1 :(得分:0)

您可以执行以下操作来检查已知字符串之间substring的长度。

SELECT *
FROM MyTable
WHERE MyTable.[Content] LIKE 'mystring%myotherstring'
AND LEN(SUBSTRING([Content],LEN('mystring'), LEN([Content])-LEN('mystring') -LEN('myotherstring'))) <= 5