如何在SQL中声明和使用变量

时间:2018-07-23 07:42:40

标签: sql variables

这是我的查询-请在下面的查询中使用变量[以粗体标记的变量]

create view cost_sheetNO (cost_No, line_No, EC, ATE, SP, E_GMValue, E_GMperc)
as  
    select 
        Vcost_sheet_line.[Cost Sheet No_], 
        Vsales_line.[Costsheet No_], 
        Vcost_sheet_line.[Landing Price],
        (select SUM(Vcost_sheet_line.[Landing Price]) 
         from Vcost_sheet_line 
         where Vsales_line.[Costsheet No_] = Vcost_sheet_line.[Cost Sheet No_]),
        Vcost_sheet_line.[List Price] * Vcost_sheet_line.[Special Vendor Discount _],
        (select declare @a decimal = sales_headerSO.OV - sales_headerSO.EC 
         from sales_headerSO), 
        (select @a - sales_headerSO.EC 
         from sales_headerSO)
    from 
        Vcost_sheet_line, Vsales_line 
    where 
        Vsales_line.[Costsheet No_] = Vcost_sheet_line.[Cost Sheet No_] 

谢谢

2 个答案:

答案 0 :(得分:1)

视图没有参数,但是您可以实现一个表格函数(您的代码看起来像SQL Server),以根据参数获得相同的结果。

public static function getInboxMessages($user_id, $limit = 40, $offset = 0, $search_key = null)
{
    return Message::hasSearch($search_key)->select("*", DB::raw("MAX(id) as max_id"))->where(function ($sql) use (
        $user_id
    ) {
        $sql->where('message_to', '=', $user_id);
        $sql->orWhere('message_from', '=', $user_id);
    })->where(function ($sql) use ($user_id) {
        $sql->where('delete_one', '<>', $user_id);
        $sql->where('delete_two', '<>', $user_id);
    })->with([
        'sender' => function ($q) {
            $q->select('id', 'uid', 'username', 'full_name', 'picture');
        }
    ])->with([
        'receiver' => function ($q) {
            $q->select('id', 'uid', 'username', 'full_name', 'picture');
        }
    ])->orderBy('max_id', 'DESC')->groupBy('chat_channel')->offset($offset)->limit($limit)->get();
}

答案 1 :(得分:0)

State

如果我正确理解您的问题