1

Below is my query where i want to check whether record from TABLE A is being used in TABLE B and based on that i am returning 'Y' and 'N'.

SELECT DISTINCT 
    ca.ID,
    IF(da.AM_SYSID IS NULL, 'Y', 'N')
FROM 
    TABLEA ca
LEFT JOIN 
    TABLEB da ON ca.ID = da.AM_SYSID

but I am getting an error

The multi-part identifier could not be bound. searched for solution

I'm still unable to see my mistake.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rupak
  • 61
  • 10

3 Answers3

5

The problem is your IF command.

In SQL Server, IF is not a function, ie something that you give two arguments and a condition and it returns the appropriate argument. Instead, it evaluates the condition and starts running a new statement. This is not what you want.

The function equivalent is case. Thus, what you really want(supposing your query is correct) is this:

SELECT DISTINCT 
    ca.ID ,
    CASE 
       WHEN da.AM_SYSID IS NULL 
          THEN 'Y' 
          ELSE 'N' 
    END
FROM 
    TABLEA ca
LEFT JOIN 
    TABLEB da ON ca.ID = da.AM_SYSID
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
George Menoutis
  • 6,894
  • 3
  • 19
  • 43
1

I believe your problem is in IF statement. You need either to use CASE/WHEN or IIF.

Try this:

SELECT DISTINCT 
    ca.ID ,
    IIF(da.AM_SYSID IS NULL, 'Y', 'N') AS YourId
FROM 
    TABLEA ca
LEFT JOIN 
    TABLEB da ON ca.ID = da.AM_SYSID

More details: https://stackoverflow.com/a/63480/2524304

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Maxim Zhukov
  • 10,060
  • 5
  • 44
  • 88
1

A much better way to write this query is to use case and exists:

SELECT ca.ID,
       (CASE WHEN NOT EXISTS (SELECT 1
                              FROM TABLEB da 
                              WHERE ca.ID = da.AM_SYSID
                             )
             THEN 'Y' ELSE 'N'
        END)
FROM TABLEA ca;

Why is this better? SELECT DISTINCT incurs overhead for removing the duplicates. This version has no such overhead (assuming that ca.id is unique, a reasonable assumption for an id).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786