Select 单个 Declare 语句中的多个值

Select multiple values within a single Declare statement

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

错误:

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

Any tips on how to make @items = multiple values?

否 - 一个 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'))

你可以使用 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 的建议并将您的查询放在主查询中。