I have a table of names and addresses, which includes a postcode column. I want to strip the spaces from the postcodes and select any that match a particular pattern. I'm trying this (simplified a bit) in T-SQL on SQL Server 2005:
SELECT Replace(Postcode, ' ', '') AS P FROM Contacts WHERE P LIKE 'NW101%'
But I get the following error;
Msg 207, Level 16, State 1, Line 3 Invalid column name 'P'.
If I remove the WHERE clause I get a list of postcodes without spaces, which is what I want to search. How should I approach this? What am I doing wrong?
The REPLACE() function replaces all occurrences of a substring within a string, with a new substring.
The REPLACE SQL function is used to replace a string or substring of a string with another string in a T-SQL script, SELECT statement, UPDATE statement, SQL query or stored procedure in a Microsoft SQL database.
The Replace statement is used to replace all occurrences of a specified string value with another string value. The Replace statement inserts or replaces values in a table. Use the Replace statement to insert new rows in a table and/or replace existing rows in a table.
Don't use the alias (P
) in your WHERE
clause directly.
You can either use the same REPLACE
logic again in the WHERE
clause:
SELECT Replace(Postcode, ' ', '') AS P FROM Contacts WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
Or use an aliased sub query as described in Nick's answers.
You can reference is that way if you wrap the query, like this:
SELECT P FROM (SELECT Replace(Postcode, ' ', '') AS P FROM Contacts) innertable WHERE P LIKE 'NW101%'
Be sure to give the wrapped select an alias, even unused (SQL Server doesn't allow it without one IIRC)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With