I am trying to convert spaces from a string into an OR statement.
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
I know that the above query is really looking for users where
postcode = '2130 OR postcode = 2602'
I really want to find users where
postcode = '2130' OR postcode = '2602'
Any ideas or direction on what I should be googling?
Update
I ended up combining the methods suggested by Albin Sunnanbo and Falcon. The function method suggested by Will Hughes was a lot more elegant but I would prefer not to use functions in this particular installation.
Here is my final query with some added cleaning features.
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