SELECT with a Replace()

前端 未结 8 1013
执念已碎
执念已碎 2021-01-31 09:03

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 tryin

相关标签:
8条回答
  • 2021-01-31 09:17

    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.

    0 讨论(0)
  • 2021-01-31 09:17

    To expand on Oded's answer, your conceptual model needs a slight adjustment here. Aliasing of column names (AS clauses in the SELECT list) happens very late in the processing of a SELECT, which is why alias names are not available to WHERE clauses. In fact, the only thing that happens after column aliasing is sorting, which is why (to quote the docs on SELECT):

    column_alias can be used in an ORDER BY clause. However, it cannot be used in a WHERE, GROUP BY, or HAVING clause.

    If you have a convoluted expression in the SELECT list, you may be worried about it 'being evaluated twice' when it appears in the SELECT list and (say) a WHERE clause - however, the query engine is clever enough to work out what's going on. If you want to avoid having the expression appear twice in your query, you can do something like

    SELECT c1, c2, c3, expr1
    FROM
        ( SELECT c1, c2, c3, some_complicated_expression AS expr1 ) inner
    WHERE expr1 = condition
    

    which avoids some_complicated_expression physically appearing twice.

    0 讨论(0)
  • 2021-01-31 09:21

    This will work:

    SELECT Replace(Postcode, ' ', '') AS P
    FROM Contacts
    WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
    
    0 讨论(0)
  • 2021-01-31 09:26

    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)

    0 讨论(0)
  • 2021-01-31 09:30

    You have to repeat your expression everywhere you want to use it:

    SELECT Replace(Postcode, ' ', '') AS P
    FROM Contacts
    WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
    

    or you can make it a subquery

    select P
    from (
    SELECT Replace(Postcode, ' ', '') AS P
    FROM Contacts
    ) t
    WHERE P LIKE 'NW101%'
    
    0 讨论(0)
  • 2021-01-31 09:31

    You are creating an alias P and later in the where clause you are using the same, that is what is creating the problem. Don't use P in where, try this instead:

    SELECT Replace(Postcode, ' ', '') AS P FROM Contacts
    WHERE Postcode LIKE 'NW101%'
    
    0 讨论(0)
提交回复
热议问题