多选存储过程

时间:2015-06-25 08:12:49

标签: mysql stored-procedures

我试图从一个表中做多个选择,但它只显示了最后一个选择语句。

CREATE PROCEDURE `usp_GetStockCard` (IN Matecode varchar(10))
BEGIN
    (select tran_date  as tran_date
        from TM_matbalance
        where Mate_code=Matecode);

    (select Mate_code as Mate_code
        from TM_matbalance
        where Mate_code=Matecode);    

    (select tran_qtyx as Qty_in 
        from TM_matbalance
        where tran_type='IN'
        and mate_code=matecode);

    (select tran_qtyx as Qty_out 
        from TM_matbalance
        where  tran_type='OUT'
        and mate_code=matecode);    
    END

我尝试在每个select语句后将分号更改为逗号,但它说语法错误:缺少'分号'。 请帮忙。

2 个答案:

答案 0 :(得分:0)

您需要将查询结构化为一个,或者将参数传递给存储过程以选择所需的输出/查询,重新构建您需要的查询:

`CREATE PROCEDURE `usp_GetStockCard` (IN Matecode varchar(10))
BEGIN
(select tran_date  as tran_date, Mate_code as Mate_code, tran_qtyx as Qty
    from TM_matbalance
    where Mate_code=Matecode
    and (tran_type='IN' or tran_type='OUT');
END`

如果您有ID列,请尝试此操作:

SELECT coalesce(ta.id, tb.id) as tran_id, coalesce(ta.tran_date, tb.tran_date)  as tran_date, coalesce(ta.Mate_code, tb.Mate_code)  as Mate_code, ta.tran_type as Qty_In, tb.tran_type as Qty_Out
from (select ta.*
  from TM_matbalance ta
  where ta.tran_type = 'IN'
and Mate_code=Matecode
 ) ta full outer join
 (select tb.*
  from TM_matbalance tb
  where tb.tran_type = 'OUT'
and Mate_code=Matecode
 ) tb
 on ta.id = tb.id ;

如果您不需要返回ID列,则只需将“id”替换为ID列的名称,然后移除coalesce(ta.id, tb.id) as tran_id

答案 1 :(得分:0)

我看着你的问题,我想我解决了。

基本上有两个问题,第一个是根据Tran_Type列(IN或OUT)中的值将您的Tran_Qtyx列变为Qty_In和Qty_Out的表格转移...您使用此查询解决的那部分问题

FragmentB

注意:在你想要的结果中我只看到'MAT001'作为Mate_Code,所以我坚持在这个解决方案中并从结果中排除MAT002。

有关数据透视表的更多信息,您可以阅读here,在那里您可以找到一个很好看的链接,在那里您可以找到很多关于mysql查询的内容。

问题的第二部分是获取Qty_Balance列。类似的问题已经解决here。这是如何根据前一行中的值计算行值。

因此,您的完整查询可能如下所示:

SELECT Tran_Date, Mate_Code,
       SUM(CASE WHEN Tran_Type = 'IN' THEN Tran_Qtyx ELSE 0 END) Qty_In,
       SUM(CASE WHEN Tran_Type = 'OUT' THEN Tran_Qtyx ELSE 0 END) Qty_Out
FROM myTable
WHERE Mate_Code = 'MAT001'
GROUP BY DATE(Tran_Date)

注意:可能只认为你应该在这里更改表名,它应该有效。

以下是SQL Fiddle,您可以看到它是如何工作的!

GL!

相关问题