查询由新行分隔的模式

时间:2016-10-22 07:09:55

标签: sql-server sql-like

我有一个表(defect),其中一列存储文本。本文中的每一行代表一个版本。 (这是运行microsoft SQL的clearquest数据库,通过JDBC访问)

例如,以下数据表示修复的三个版本。

defect version_fixed
1      2015.1.1
2      2015.1.1\n2015.1.13
3      2015.1.12\n2015.1.1 
4      2015.1.12\n2015.1.1\n2015.1.13 
5      2015.1.13\n2015.1.10 
5      2015.1.100

如您所见,版本未存储在订单中。它可以出现在任何地方。

我感兴趣的是修复版修复的所有行包含" 2015.1.1"。但我的查询要么获得更多行,要么跳过一些

version_fixed like '%2016.1.1%' (gets row 5 as it matches the pattern)
version_fixed like '%2016.1.1\n'(does not get any thing.)

我正在寻找查询以获取2015.1.1的确切列表

defect version_fixed
1      2015.1.1
2      2015.1.1\n2015.1.13
3      2015.1.12\n2015.1.1 
4      2015.1.12\n2015.1.1\n2015.1.13 

如何查询文本与"精确字符串匹配的位置,由新行或文本结尾分隔"。逃避新线路的正确方法是什么?

附注:当前解决方案是获取所有记录(包括不需要的记录,然后过滤掉不正确的结果)

2 个答案:

答案 0 :(得分:1)

你可以试试这个。它依赖于Sql Server在断行时将新行添加到字符串。

create table defect( version_fixed varchar(max) )
insert into defect( version_fixed ) 
values ( '2015.1.1' )
, ( '2015.1.1
2015.1.13' )
, ( '2015.1.12
2015.1.1' )
, ( '2015.1.12
2015.1.1
2015.1.13')
, ( '2015.1.13
2015.1.10' )
, ( '2015.1.100' )

-- break to a new line and Sql Server will include the newline character in the string
select * from defect where version_fixed like '%2015.1.1
%' or version_fixed like '%2015.1.1' 

答案 1 :(得分:0)

您可以如下所示:

WHERE '\' + version_fixed  + '\' LIKE '%2015.1.1\%'

此解决方案会取消您的样本数据。