我想在 user_id app_id 上加入2个表'地址''user_info' (这是一个数字,或者它是null),就像这两个例子一样:

select * from user_info 
left outer join addresses on addresses.user_id = user_info.user_id 
and addresses.app_id is null

select * from user_info 
left outer join addresses on addresses.user_id = user_info.user_id 
and addresses.app_id = 1234

app_id应该是多么复杂,我写了一个函数来返回它。它返回一个字符串,例如“is null”。或“= 1234”。 我试图用这种语法来调用它:

select * from user_info 
left outer join addresses on addresses.user_id = user_info.user_id 
and addresses.app_id dbo.fnGetAppId(addresses.user_id)

我收到此错误:

  

Msg 4145,Level 15,State 1,Line 3 An   表达非布尔类型   在上下文中指定的   条件是预期的,靠近'dbo'。

我想保持查询非常简单,因为它不必确定函数是否返回null。

您能否建议保持调用查询非常简单的最佳方法?

(我在sql server 2005中。)

有帮助吗?

解决方案

NULL!= NULL。如果address.app_id = NULL或fnGetAppID = NULL,则比较将失败。我会把比较写成:

coalesce(address.app_id,'NULLSTRING')= coalesce(dbo.fnGetAppID(addresses.user_id),'NULLSTRING')

其他提示

看起来你只是错过了一个=符号

addresses.app_id dbo.fnGetAppId(addresses.user_id)

而不是

addresses.app_id = dbo.fnGetAppId(addresses.user_id)

因此,如果fnGetAppId为null,则此查询如下所示?

select * from user_info left outer join addresses on addresses.user_id = user_info.user_id and null

我怀疑这是你想要的。 :)

在调用查询之前,您可能希望对逻辑进行简单检查,以便正确处理fnGetAppId的null,而Clyde提到您还需要一个非符号的=符号

正如詹姆斯布莱克指出的那样,你有AND你可能想要的地方。除此之外,我建议你把函数作为一个布尔函数(将address.app_id作为一个参数传递给它),因此它可以适当地执行IS NULL或= 1234(Bill的COALESCE解决方案确实很聪明,但是进行了适当的比较函数内部更直接,IMO)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top