0

I have this T-SQL statement

select a.CODE 
from MASTER..MASTERADD a, MASTER..MASTER b 
where a.TELO = '18002000047' 
  OR a.MOBILE = '18002000047' 
  AND b.TPIN = '42589' 
  and a.code = b.code

AND

select a.CODE 
from MASTER..MASTERADD a, MASTER..MASTER b 
where a.TELO = '18001147722' 
  OR a.MOBILE = '18001147722' 
  AND b.TPIN = '56783' 
  and a.code = b.code

The first statement returns 1 result (single line) (CODE)

The second returns 'CODE' but repeated like about 9000+ times.

What am I doing wrong?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
John Dcruz
  • 61
  • 1
  • 8
  • 3
    A few things you are missing some parentheses around your `(a.TELO = '18001147722' OR a.MOBILE = '18001147722')`, second I'd strongly suggest using `JOIN` syntax instead of using a comma between your tables a the join criteria in a `where` clause. – Taryn Jun 10 '14 at 15:53
  • 2
    [Bad habits to kick : using old-style JOINs](https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins) - that old-style *comma-separated list of tables* style was discontinued with the ANSI-**92** SQL Standard (more than **20 years** ago) – marc_s Jun 10 '14 at 15:57

2 Answers2

2

The problem is the order of operations of the keywords OR and AND

What you need to do is add some parenthesis. You are most likely looking for this logic:

SELECT a.CODE
FROM MASTER..MASTERADD a
JOIN MASTER..MASTER b
    ON a.code = b.code
WHERE (
        a.TELO = '18001147722'
        OR a.MOBILE = '18001147722'
        )
    AND b.TPIN = '56783'
Community
  • 1
  • 1
arserbin3
  • 6,010
  • 8
  • 36
  • 52
0

It looks like you need parentheses around your OR in the WHERE part of your statement:

SELECT
    MASTERADD.CODE
FROM
    MASTER..MASTERADD MASTERADD
    INNER JOIN
    MASTER..MASTER MASTER
    ON
        MASTERADD..CODE = MASTER.CODE
WHERE
    (
    MASTERADD..TELO = '18001147722'
    OR
    MASTERADD..MOBILE = '18001147722'
    )
    AND
    MASTER.TPIN = '56783'

This may not address your problem however. You have two different conditions (different telephone numbers and pin numbers), so why wouldn't you expect different results?

Less importantly, I would suggest you clean up the syntax on your code because it makes identifying problem areas and later reverse engineering easier to facilitate.

K Richard
  • 1,924
  • 2
  • 22
  • 43
  • Actually the problem is this "The second returns 'CODE' but repeated like about 9000+ times." So, I get the code = "same code" but it's repeated like 9000+ times. – John Dcruz Jun 11 '14 at 05:44