0

我正在尝试将字符串中的空格转换为 OR 语句。

Declare @postcodes varchar(128)
SET @postcodes = '2130 2602' --this input will be postcodes separated by a space (I'm in Australia so the postcodes are only 4 numbers long)
SET @postcodes = REPLACE(@postcodes, ' ', ' OR postcode = ') --I know this isn't right but it shows what I am trying to achieve
SELECT *
FROM users
WHERE postcode = @postcodes

我知道上面的查询确实是在寻找用户

postcode = '2130 OR postcode = 2602'

我真的很想在哪里找到用户

postcode = '2130' OR postcode = '2602'

关于我应该搜索什么的任何想法或方向?

更新

我最终结合了Albin SunnanboFalcon建议的方法。Will Hughes建议的函数方法要优雅得多,但我不想在这个特定的安装中使用函数。

这是我的最终查询,添加了一些清洁功能。

Declare @postcodes varchar(128)
SET @postcodes = '2130 2602 2000'

--Postcode cleaning
SET @postcodes = REPLACE(@postcodes,';',' ') --removes ";"
SET @postcodes = REPLACE(@postcodes,',',' ') --removes ","
SET @postcodes = (LTRIM(RTRIM(@postcodes))) --trim white space
SET @postcodes = REPLACE(@postcodes,'  ',' ') --removes double spaces
SET @postcodes = REPLACE(@postcodes,'  ',' ') --removes double spaces again
SET @postcodes = '''' + REPLACE(@postcodes,' ',''',''') + '''' --adds ' to @postcodes

DECLARE @SQLString nvarchar(MAX);
SET @SQLString = N'
SELECT * 
FROM users
WHERE postcode IN(' + @postcodes + ')';

EXECUTE sp_executesql @SQLString;

SELECT @SQLString AS SQLString --This part serves no purpose, it just shows you what the query looks like
4

3 回答 3

3

您可以使用此Stack Overflow Question的答案拆分字符串。

创建此函数后,您可以像这样使用它:

Declare @postcodes varchar(128)
SET @postcodes = '2130 2602'

SELECT *
FROM users
   JOIN dbo.Split(' ',@postcodes) postcodes 
   ON users.postcode = postcodes.s
于 2012-05-08T04:28:56.383 回答
2

我会构建一个字符串并使用 sp_executesql 执行

Declare @postcodes varchar(128)
SET @postcodes = '2130 2602'
SET @postcodes = REPLACE(@postcodes, ' ', ',')

DECLARE @SQLString nvarchar(MAX);
SET @SQLString = N'SELECT *
FROM users
WHERE postcode IN (' + @postcodes ')';

EXECUTE sp_executesql @SQLString;

不过要小心 SQL 注入。

于 2012-05-08T04:30:29.053 回答
2
Declare @postcodes varchar(128)
SET @postcodes = '2130 2602'  
SET @postcodes = CONCAT('"',REPLACE(@postcodes, ' ', '" OR postcode = "'),'"') -- Now it will make it "2130" OR postcode = "2602"-------- 

SELECT *
FROM users
WHERE postcode = @postcodes

希望这可以帮助

于 2012-05-08T05:35:41.593 回答