简体   繁体   English

SQL:创建字符串数组并查询=像数组中的所有字符串一样

[英]SQL: creating a string array and query = like all strings in array

I have SQL Server 2005 Report that takes a parameter in a query string that searches customer names. 我有SQL Server 2005报表,该报表在查询客户名称的查询字符串中采用参数。 The problem is some customers like to put in a middle initial so when the user 'John Smith' this does not bring up 'John Q. Smith'. 问题是有些客户喜欢在中间加上一个大写字母,因此当用户“ John Smith”使用该字母时,不会出现“ John Q. Smith”。

Using only sql, how would I split a string into an array by whitespace then search records matching each string in the array to the result? 仅使用sql,我将如何通过空格将字符串拆分为数组,然后搜索与数组中每个字符串匹配的结果的记录?

You can use a user-defined split function, like the one here and use that something like this: 您可以使用用户定义的拆分功能(例如此处的功能),并使用类似以下内容的功能:

SELECT *
FROM SomeTable t
WHERE NOT EXISTS (SELECT * FROM dbo.Split('John Smith', ' ') s WHERE t.NameColumn NOT LIKE '%' + s.Data + '%')

You'd need to see how this performs for you 您需要查看它如何为您执行

Edit: Original version didn't do what you want - I glossed over the fact you want to match on ALL parts, whereas it would have returned all "John"s and all "Smith"s. 编辑:原始版本没有满足您的要求-我掩盖了您希望在所有零件上都匹配的事实,而它会返回所有“约翰”和所有“史密斯”。 Corrected to match on ALL parts now. 已更正以匹配所有零件。

Try this sql server 2005 试试这个SQL Server 2005

DECLARE @UserName VARCHAR(MAX)

SELECT @UserName = 'John Smit'

DECLARE @User TABLE(
        UserName VARCHAR(MAX)
)

INSERT INTO @User (UserName) SELECT 'John Smit'
INSERT INTO @User (UserName) SELECT 'John Q. Smit'

SELECT  *
FROM    @User
WHERE   UserName LIKE REPLACE(@UserName, ' ', '%')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM