在单个Declare语句中选择多个值

时间:2016-02-24 17:18:31

标签: sql variables declare

DECLARE @account VARCHAR(12)  
SET @account = '49943725'  

DECLARE @items VARCHAR(5)  
SET @items = (SELECT item_no FROM transactions   
               WHERE account = @account   
               AND item_no IN ('81','101','108','112','113','118','187','189','190','192','193','194','195'))

SELECT 
    property, CONVERT(VARCHAR(10), account) AS account,
    CONVERT(VARCHAR(5), item_no) AS item_no,
    CONVERT(VARCHAR(9), amount) AS amount,  
    CONVERT(VARCHAR(9), amt_paid) AS amt_paid, 
    status,
    CONVERT(VARCHAR(8), tran_id) AS tran_id, 
    CONVERT(VARCHAR(11), post_date) AS post_date, 
    tran_code, 
    CONVERT(VARCHAR(25), notes) AS notes, 
    clk, invoice, charge_property, * 
FROM 
    transactions 
WHERE 
    account = @account AND item_no = @items

错误:

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

2 个答案:

答案 0 :(得分:1)

  

有关如何使@items =多个值的任何提示?

否 - VARCHAR(5)变量只能包含一个值。你可以,如何将你的列表作为子查询嵌入:

SELECT 
     property, 
     CONVERT(VARCHAR(10), account) AS account,
     CONVERT(VARCHAR(5), item_no) AS item_no,
     CONVERT(VARCHAR(9), amount) AS amount,  
     CONVERT(VARCHAR(9), amt_paid) AS amt_paid, status,
     CONVERT(VARCHAR(8), tran_id) AS tran_id, 
     CONVERT(VARCHAR(11), post_date) AS post_date, tran_code, 
     CONVERT(VARCHAR(25), notes) AS notes, clk, invoice, charge_property, *
FROM transactions 
WHERE account = @account 
AND item_no IN (SELECT item_no FROM transactions   
               WHERE account = @account   
               AND item_no IN        
                ('81','101','108','112','113','118','187','189','190','192','193','194','195'))

答案 1 :(得分:0)

您可以使用table variable

DECLARE @Account VARCHAR(12) = '49943725';
DECLARE @Items TABLE (ItemNo VARCHAR(5));

INSERT @Items (Item_no)
SELECT  item_no 
FROM    transactions   
WHERE   account = @account   
AND     item_no IN ('81','101','108','112','113','118','187','189','190','192','193','194','195');

然后在实际查询中使用IN

AND     item_no IN (SELECT ItemNo FROM @Items);

虽然除非您获取项目的查询比您所显示的更复杂,但您也可以遵循D Stanley的建议并将查询放在主查询中。