How to execute Stored Procedure from Laravel

2019-01-10 23:20发布

问题:

I need to execute a stored procedure after my form submits data. I have the stored procedure working like I want it, and I have my form working properly. I just do not know the statement to execute the sp from laravel 5.

it should be something like this: execute my_stored_procedure. but I can not seem to find anything like that online.

回答1:

Try something like this

DB::select('exec my_stored_procedure("Param1", "param2",..)');

or

DB::select('exec my_stored_procedure(?,?,..)',array($Param1,$param2));

Try this for without parameters

DB::select('EXEC my_stored_procedure')


回答2:

You can also do this:

DB::select("CALL my_stored_procedure()");


回答3:

for Laravel 5.4


DB::select(DB::raw("exec my_stored_procedure"));

if you want to pass parameters:

DB::select(DB::raw("exec my_stored_procedure :Param1, :Param2"),[
    ':Param1' => $param_1,
    ':Param2' => $param_2,
]);


回答4:

for Laravel 5.5

DB::select('call myStoredProcedure("p1", "p2")');

or

DB::select('call myStoredProcedure(?,?)',array($p1,$p2));

no parameter

DB::select('call myStoredProcedure()')


回答5:

Working code with Laraval 5.6,

DB::select('EXEC my_stored_procedure ?,?,?',['var1','var2','var3']);


回答6:

Running the Microsoft SQL Server Stored Procedure (MS SQL Server) using PHP Laravel framework. If you are trying to run SP using Laravel Model then you can use following two approaches.

$submit = DB::select(" EXEC ReturnIdExample ?,?", array( $paramOne ,$paramTwo ) ); 

$submit = DB::select(" EXEC ReturnIdExample $paramOne,$paramTwo ");

If incase you are passing the Varchar Parameter then use the following:

$submit = DB::select(" EXEC ReturnIdExample '$paramOne', '$paramTwo' ");

If you are just passing parameter which are of INT or BIGINT then this should work and you can get the return from SP:

$submit = DB::select(" EXEC ReturnIdExample $paramOne,$paramTwo ");

Once the stored procedure is executed the values will be present in the $submit in the form of array, you need to loop through it and access the required columns.

foreach($submit  as $row)
{

echo $row->COLUMN1;
echo $row->COLUMN2;
echo $row->COLUMN3;

}


回答7:

For version 5.5 use CALL:

return DB::select(DB::raw('call store_procedure_function(?)', [$parameter]))


回答8:

app('db')->getPdo()->exec('exec my_stored_procedure');