需要匹配SQL Server中varchar列中的完全字符串

时间:2017-04-04 04:52:33

标签: sql-server function tsql sql-server-2014

我有两个部分的问题,我从列中拉出所有#hashtags以显示#hashtags是"趋势"用于在SSRS报告上显示的特定时间范围。然后我有一个子报告,用户可以在其中单击#hashtag并将其带到#hashtag出现的表中的所有记录。

要从表中提取#hashtags,这个thread向我展示了如何使用两个函数和交叉应用来完成此专长。

现在我试图在SQL Server中的表中找到varchar(max)列中文本字符串的完全匹配。我当前的查询使用LIKE语句:

ticketDescription LIKE  '%' + @paramHashtag + '%'

这提出了一个问题,因为我在#update和#updateinfo中有类似的#hashtags,而LIKE语句在搜索#update hashtags时会返回#updateinfo hashtags。

我尝试使用WHERE CONTAINS (ticketDescription, @paramHashtag),但我们没有启用全文,我不确定这是否可能。

如果不能选择全文搜索,是否可以查找将传递给查询的参数的完全匹配?

以下是故障单说明中的示例数据:

CREATE TABLE [dbo].[Trending](
[TicketDescription] [varchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

TicketDescription列中的值:

#Update  Corrected last name and driver's license number.
#Update  Update customer's last name.
#Update  Update last name, address
#update - Profile updated. Corrected last name.
#updateinfo
#updateinfo
#updateinfo
#updateinfo
#Update  Update residency status
#update #SSNdiscrepancy   John Doe called in claiming this was their SSN, please advise.
#update  Updated residency status
#Update  Changed residency from in-state to out-of-state
#Update  Updated Customer's last name
#updateinfo
#updateinfo
#Update - updated customer's last name

1 个答案:

答案 0 :(得分:1)

以下是一个示例,说明如何编写一个应该提供预期结果的查询(通过检查主题标签上的匹配项,然后检查不是字母或数字的字符 - 例如a hashtag之后的空格,逗号等:

DECLARE @T TABLE (TicketDescription VARCHAR(MAX));
INSERT @T VALUES 
('junk text #Update  Corrected last name and driver''s license number.'),
('more junk text#Update  Update customer''s last name.'),
('asdfadsf #Update  Update last name, address'),
('#update - Profile updated. Corrected last name.'),
('#updateinfo'),
('#updateinfo'),
('#updateinfo'),
('#updateinfo'),
('#Update  Update residency status'),
('#update #SSNdiscrepancy   John Doe called in claiming this was their SSN, please advise.'),
('#update  Updated residency status'),
('#Update  Changed residency from in-state to out-of-state'),
('asdfasdfadf#Update  Updated Customer''s last name'),
(' asdfadsf #updateinfo'),
('asdf #updateinfo'),
('#Update - updated customer''s last name'),
('#Update'),
('#Update,example with a comma after hashtag');

DECLARE @param VARCHAR(255) = '#update';

SELECT TicketDescription
FROM @T
WHERE TicketDescription LIKE '%' + @param + '[^A-Z0-9]%' -- Hashtag + something that isn't a letter or number.
OR RIGHT(TicketDescription, LEN(@param)) = @param; -- Or it matches the very last part of the given TicketDescription.