Solved

Having an issue with the MSSQL select statement using the replace function

Posted on 2014-02-19
3
357 Views
Last Modified: 2014-02-19
Hi All,

   I'm trying to do a select statement in MSSQL 2012 and PHP 5.3 from a column filled with telephone numbers.  Some have spaces in between, some have hyphens, some have none.  I tried the following select statement:

select *, replace(dbo.MERCHANT.CONTACT_PHONE, '-', '') as CTPHONE from dbo.MERCHANT where CONTACT_PHONE = '7781234567'

   But it doesn't return any rows.  I've tried inside the SQL Server Management Studio as well, but no rows are returned.

   I've tried googling but I can't seem to find any help there.

Thanks!!
Zack
0
Comment
Question by:IT Tech
3 Comments
 
LVL 11

Accepted Solution

by:
Simone B earned 250 total points
Comment Utility
The CONTACT_PHONE still has dashes in it, so your Where clause won't be satisfied.

Try this:

select *, replace(dbo.MERCHANT.CONTACT_PHONE, '-', '') as CTPHONE from dbo.MERCHANT where replace(dbo.MERCHANT.CONTACT_PHONE, '-', '') = '7781234567'
0
 
LVL 65

Assisted Solution

by:Jim Horn
Jim Horn earned 250 total points
Comment Utility
>select *, replace(dbo.MERCHANT.CONTACT_PHONE, '-', '') as CTPHONE from dbo.MERCHANT where CONTACT_PHONE = '7781234567'

The SQL query engine processes the SELECT clause of a query dead last, so if you have a row WHERE CONTACT_PHONE='778-123-4567', then you'll have to search for it with all of the dashes/underscore/whatever, regardless of what the replace() does in the SELECT.

Otherwise, if you want to avoid that, then throw it into a subquery.   Something like..

SELECT a.*, a.CTPHONE
FROM (
   select *, replace(dbo.MERCHANT.CONTACT_PHONE, '-', '') as CTPHONE
   from dbo.MERCHANT ) a
where a.CONTACT_PHONE = '7781234567'
0
 

Author Closing Comment

by:IT Tech
Comment Utility
Thanks very much!!!
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
These days socially coordinated efforts have turned into a critical requirement for enterprises.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
The viewer will learn how to count occurrences of each item in an array.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now