如何从结果中检查多个id在SQL中连续多个id列?

时间:2011-10-20 00:05:42

标签: sql sql-server tsql

我们有一张发票表。发票具有所有者和客户,两个id字段都链接到资源表。资源表包含可能在其下具有“子”业务的企业。我有一个查询,检查当前业务是否在owner_id或customer_id中,如下所示:

SELECT * FROM invoices i WHERE @BusinessId IN ( i.owner_id, i.customer_id )

我目前遇到的问题是我需要验证商家或其子商家是否在owner_id或customer_id中。我有一个函数,如果我这样查询它,则返回一个包含资源表中的业务ID的表:

select business_id from  dbo.vfn_child_business(@BusinessId , 'Y')

'Y'参数基本上返回主要父级以及结果中的子业务ID(主要是查找业务的子业务并包括其自身)。

我无法弄清楚如何查询

SELECT * from Invoices
where ANY OF MY RESULTS FROM CHILD BUSINESS FUNCTION IN ( i.owner_id, i.customer_id ).

我试过了:

... WHERE (select business_id 
           from  dbo.vfn_child_business(@BusinessId , 'Y'))
    IN ( i.owner_id, i.customer_id )

但是我收到了这个错误:

  

子查询返回的值超过1。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   表达。

请有人帮忙吗?

2 个答案:

答案 0 :(得分:1)

我没有对此进行测试,但EXISTS谓词可能对此有所帮助:

WITH children AS
    (SELECT business_id
     FROM dbo.vfn_child_business(@BusinessId , 'Y'))
SELECT
    i.*
FROM
    Invoices AS i
WHERE
    EXISTS
        (SELECT 1
         FROM children
         WHERE children.business_id IN ( i.owner_id, i.customer_id ))

答案 1 :(得分:0)

您是否尝试将该功能加入到桌面?

SELECT
  invoices.*
FROM
  invoices
INNER JOIN
  dbo.vfn_child_business(@BusinessId , 'Y')  AS child_business
    ON invoices.owner_id    = child_business.business_id
    OR invoices.customer_id = child_business.business_id

如果这会导致重复,请使用DISTINCT或GROUP BY。