Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT with a Replace()

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?

like image 940
Andy Johnson Avatar asked Apr 16 '10 10:04

Andy Johnson


People also ask

What does replace () do in SQL?

The REPLACE() function replaces all occurrences of a substring within a string, with a new substring.

Can we use Replace in select statement in SQL?

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.

How do you replace a value in a select statement?

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.


2 Answers

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.

like image 176
Oded Avatar answered Sep 21 '22 19:09

Oded


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)

like image 23
Nick Craver Avatar answered Sep 20 '22 19:09

Nick Craver