使用未在mssql中运行的变量选择查询

时间:2015-12-16 11:22:27

标签: sql-server variables select

在MSSQL2014中使用变量时,选择查询无效 我的架构是: -

    CREATE TABLE product 
    (idproduct int, name varchar(50), description varchar(50), tax decimal(18,0))


INSERT INTO product
    (idproduct, name, description,tax)
VALUES
    (1, 'abc', 'This is abc',10),
    (2, 'xyz', 'This is xyz',20),
    (3, 'pqr', 'This is pqr',15)


CREATE TABLE product_storage 
    (idstorage int,idproduct int,added datetime, quantity int, price decimal(18,0))


INSERT INTO product_storage 
    (idstorage,idproduct, added, quantity,price)
VALUES
    (1, 1, 2010-01-01,0,10.0),
    (2, 1, 2010-01-02,0,11.0),
    (3, 1, 2010-01-03,10,12.0),
    (4, 2, 2010-01-04,0,12.0),
    (5, 2, 2010-01-05,10,11.0),
(6, 2, 2010-01-06,10,13.0),
(7, 3, 2010-01-07,10,14.0),
(8, 3, 2010-01-07,10,16.0),
(9, 3, 2010-01-09,10,13.0)

我在命令下面执行: -

declare @price1 varchar(10)


SELECT p.idproduct, p.name, p.tax,
[@price1]=(SELECT top 1 s.price
        FROM product_storage s
        WHERE s.idproduct=p.idproduct AND s.quantity > 0
        ORDER BY s.added ASC),
 (@price1 * (1 + tax/100)) AS [price_with_tax]
FROM product p

;

这在MSSQL中不起作用,请帮帮我。 详细检查http://sqlfiddle.com/#!6/91ec2/296

我的查询在MYSQL中工作 检查详细信息: - http://sqlfiddle.com/#!9/a71b8/1

3 个答案:

答案 0 :(得分:3)

尝试此查询

SELECT 
    p.idproduct
    , p.name
    , p.tax
    , (t1.price * (1 + tax/100)) AS [price_with_tax]
FROM product p
inner join 
(
    SELECT ROW_NUMBER() over (PARTITION by s.idproduct order by s.added ASC) as linha, s.idproduct, s.price 
    FROM product_storage s
    WHERE s.quantity > 0    
) as t1
    on t1.idproduct = p.idproduct and t1.linha = 1

答案 1 :(得分:1)

试试这样:

解释:您不能动态使用变量"但是您可以在APPLY中逐行计算......

SELECT p.idproduct, p.name, p.tax,
       Price.price1,
       (price1 * (1 + tax/100)) AS [price_with_tax]
FROM product p
CROSS APPLY (SELECT top 1 s.price
             FROM product_storage s
             WHERE s.idproduct=p.idproduct AND s.quantity > 0
             ORDER BY s.added ASC) AS Price(price1)

;

编辑:你的小提琴使用了错误的文字日期格式,试试这个:

INSERT INTO product_storage 
    (idstorage,idproduct, added, quantity,price)
VALUES
    (1, 1, '20100101',0,10.0),
    (2, 1, '20100102',0,11.0),
    (3, 1, '20100103',10,12.0),
    (4, 2, '20100104',0,12.0),
    (5, 2, '20100105',10,11.0),
    (6, 2, '20100106',10,13.0),
    (7, 3, '20100107',10,14.0),
    (8, 3, '20100108',10,16.0),
    (9, 3, '20100109',10,13.0)

答案 2 :(得分:0)

这是正确的SQL Server架构和查询运行完美的Shnugo回复。

...
@Override
public void onClick(View v) {
...//Some logic here that sets visibility to true or false
    recyclerView.getChildAt(position).checkboxIsVisible=true;
...
    adapter.notifyDataSetChanged();
}