简体   繁体   English

多部分标识符不能在SQL中绑定

[英]The multi-part identifier could not be bound in SQL

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'. 以下是我要查询的查询,其中我想检查表B中是否使用了表A中的记录,并基于此返回“ Y”和“ 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. 我仍然看不到我的错误。

The problem is your IF command. 问题是您的IF命令。

In SQL Server, IF is not a function, ie something that you give two arguments and a condition and it returns the appropriate argument. 在SQL Server中, IF不是函数,也就是说,您提供两个参数和一个条件,然后它返回适当的参数。 Instead, it evaluates the condition and starts running a new statement . 相反,它将评估条件并开始运行新语句 This is not what you want. 这不是您想要的。

The function equivalent is case . 功能等效为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

I believe your problem is in IF statement. 我相信您的问题出在IF语句中。 You need either to use CASE/WHEN or IIF . 您需要使用CASE/WHENIIF

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 更多详细信息: https : //stackoverflow.com/a/63480/2524304

A much better way to write this query is to use case and exists : 编写此查询的一种更好的方法是使用caseexists

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. SELECT DISTINCT会导致删除重复项的开销。 This version has no such overhead (assuming that ca.id is unique, a reasonable assumption for an id ). 这个版本没有这种开销(假设ca.id是唯一的,对于id的合理假设)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM