测试时我想在变量中插入多个值

时间:2014-04-04 16:02:10

标签: sql sql-server reporting-services

我正在测试一些可以接受多个值的sql代码,然后使用“IN”语句对它们进行比较。我如何模拟这个进行测试。继承人我正在使用但它没有返回任何内容,这是不正确的,因为当我在SSRS报告中发送多个值时,它可以正常工作。我希望@item能够模拟报告运行时从SSRS获得的内容。

Declare
@item VarChar(100)

Set @item = ('1003932,1003933,1003934')




SELECT DISTINCT
    CUSTNAME,
    ISNULL(NAME, LOGCREATEDBY) AS 'Modified By'
    ,b.ITEMID as 'Item Id'
    ,[PRICE_NEW] as 'New Price'
    ,[PRICE_OLD] as 'Old Price'
    ,[PRICEUNIT_NEW] as 'New Unit Price'
    ,[PRICEUNIT_OLD] as 'Old Unit Price'
    ,LOGCREATEDDATE as 'Created Date' 
    ,(Select TOP 1 INVENTTRANS.DATEFINANCIAL From INVENTTRANS Where INVENTTRANS.ITEMID = @item order by INVENTTRANS.DATEFINANCIAL desc) As 'LastInvoice'
FROM PMF_INVENTTABLEMODULELOG AS b
    LEFT JOIN USERINFO ON ID = LOGCREATEDBY
    LEFT JOIN INVENTTABLE AS a on a.ITEMID in (@item)
WHERE b.ITEMID in (@item)
order by LOGCREATEDDATE  desc

3 个答案:

答案 0 :(得分:3)

不可能这样做。

我建议您将值插入表变量

declare @items_table table (id int);
insert @items_table values ('1003932'),('1003933'),('1003934');

然后将where子句更改为

WHERE b.ITEMID in (SELECT id FROM @items_table)

或者您只需修改where子句:

WHERE b.ITEMID in ('1003932','1003933','1003934')

答案 1 :(得分:1)

试试这个......

Declare @item table
( item varchar(100)
)

INSERT INTO @item
SELECT '1003932' union all
SELECT '1003933' union all
SELECT '1003934']


SELECT DISTINCT
    CUSTNAME,
    ISNULL(NAME, LOGCREATEDBY) AS 'Modified By'
    ,b.ITEMID as 'Item Id'
    ,[PRICE_NEW] as 'New Price'
    ,[PRICE_OLD] as 'Old Price'
    ,[PRICEUNIT_NEW] as 'New Unit Price'
    ,[PRICEUNIT_OLD] as 'Old Unit Price'
    ,LOGCREATEDDATE as 'Created Date' 
    ,(Select TOP 1 INVENTTRANS.DATEFINANCIAL From INVENTTRANS Where INVENTTRANS.ITEMID = @item order by INVENTTRANS.DATEFINANCIAL desc) As 'LastInvoice'
FROM PMF_INVENTTABLEMODULELOG AS b
    LEFT JOIN USERINFO ON ID = LOGCREATEDBY
    LEFT JOIN INVENTTABLE AS a on a.ITEMID in (@item)
WHERE b.ITEMID in (SELECT item from @item)
order by LOGCREATEDDATE  desc

答案 2 :(得分:0)

我遇到了同样的问题,尤其是在处理从SSRS填充的多参数变量时。这是我在一些遗留代码中找到的解决方案,我认为这非常有用。该功能的链接来自sqlfool.com的Michelle Ufford。链接:http://sqlfool.com/2011/05/string-parsing-function/

DECLARE @item VARCHAR(100)
SET @item = '1003932,1003933,1003934'

DECLARE @tblItems AS TABLE
(
    Item VARCHAR(7)
);

INSERT INTO @tblItems
        ( Item )
SELECT stringValue
FROM Database.dbo.dba_parseString_udf(@item,',')

SELECT * FROM @tblItems

在代码中插入SELECT Item FROM @tblItems代替@item应该可以解决问题。最重要的是,当您想要在SSMS中测试数据时,可以轻松填充查询,因为您只需从SSRS参数框中复制所需的参数即可。并且这个代码根本不需要使用SSRS进行修改,因此注释掉前两行代码将使您的代码准备好接受来自SSRS的多个参数。 注意:显然这只适用于在SSMS中使用存储过程来封装代码的情况。在SSRS中使用查询字符串时选择多个参数时,会出现如下错误:

  

过程或函数Database.dbo.dba_parseString_udf指定了太多参数。

看起来参数通过字符串传递给存储过程,但作为数组传递给字符串查询。