我正在尝试将字符串中的空格转换为 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 Sunnanbo和Falcon建议的方法。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