使用WHERE与多行变量

时间:2017-03-07 16:27:39

标签: sql sql-server

我有一个查询用于返回数据:

Select top 100 
       cnb.ndc_id, 
       cnb.contract_num_val, 
       cnb.quote_price, 
       cnb.eff_dt, 
       cnb.end_dt, 
       cnb.discount_pct, 
       cnb.rebate_pct
from   [NDC_ATTR] ndc 
  INNER JOIN CONTRACT_NDC_BRG cnb ON ndc.attr_val=cnb.NDC_ID
where ndc.field_id = 69 
and   cnb.contract_ndc_brg_id = @CONT;

当我运行时,我收到错误:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

我知道这是因为@CONT有多行。但这正是我所需要的。

我一直在浏览帖子,似乎不鼓励在SQL中使用循环。 (如果我错了,请纠正我)

如何返回上述查询的并集,但@CONT中的每一行都会返回每一行?

编辑:

@CONT定义:

declare @CONT varchar(50) = (   
   SELECT contract_ndc_brg_id
   FROM   contract_ndc_brg
     INNER JOIN ndc ON contract_ndc_brg.ndc_id = ndc.item_pk
   where item_id = @VALUE 
   );

3 个答案:

答案 0 :(得分:2)

编辑:我刚看到你在@cont后面的查询,这应该有效,但我个人更喜欢SqlZim给出的答案:

declare @CONT TABLE (value varchar(500)) 

SELECT contract_ndc_brg_id
FROM contract_ndc_brg
INNER JOIN ndc
ON contract_ndc_brg.ndc_id = ndc.item_pk
where item_id = @VALUE 

Select top 100 cnb.ndc_id, cnb.contract_num_val, cnb.quote_price,cnb.eff_dt, cnb.end_dt, cnb.discount_pct, cnb.rebate_pct
from [NDC_ATTR] ndc 
INNER JOIN CONTRACT_NDC_BRG cnb
ON ndc.attr_val=cnb.NDC_ID
where ndc.field_id=69 and cnb.contract_ndc_brg_id IN ( @CONT );

答案 1 :(得分:2)

如果您可以加入Option Explicit Sub getColumn() Dim ColNum As Long Dim rCell As Range Dim rRange As Range On Error Resume Next Set rRange = Workbooks(ActiveWorkbook.Name).Worksheets("Data").Range("A1:XFD1") For Each rCell In rRange If rCell.MergeArea.Cells.Count > 1 Then msgBox (rCell.Column) 'consider debug.print rCell.column End If Next rCell End Sub ,则可以删除@CONT,如下所示:

ndc

或转换为使用select top 100 cnb.ndc_id , cnb.contract_num_val , cnb.quote_price , cnb.eff_dt , cnb.end_dt , cnb.discount_pct , cnb.rebate_pct from [NDC_ATTR] ndc inner join CONTRACT_NDC_BRG cnb on ndc.attr_val = cnb.NDC_ID inner join ndc as i on cnb.ndc_id = i.item_pk where ndc.field_id = 69 and i.item_id = @VALUE ,如下所示:

exists()

答案 2 :(得分:2)

为什么要使用变量?只需将子查询插入:

 memcpy(b, a, sizeof(int)*4);