How to Execute Stored Procedures from a PLC
What Is a Stored Procedure?
A stored procedure groups a series of operations on a database
In SQL Server, system stored procedures can be found in the location below
Benefits of executing stored procedures from a PLC
There is no need to build complex SQL statements on the PLC side.
Processing can be consolidated on the database side, keeping the PLC program simple.
Search, registration, update and other processing can be reused as stored procedures.

Example
An example that calls the "sp_databases" system stored procedure, which gets the list of databases
Ladder logic

Turning the Execute flag ON starts the process of calling the stored procedure
- DB_Connect: connects to the DB
- DB_AttachProcedure: specifies the stored procedure and gets a handle
- DB_ExecuteProcedure: executes the stored procedure
- DB_DetachProcedure: releases the handle
- DB_Close: closes the connection to the DB
The parameters needed for DB_AttachProcedure are as follows
- ProcName: procedure name
- ArgIn: input parameters
- ArgOut: output parameters
- ArgInOut: in-out parameters
- ReturnVal: return value
- ResultSet: result set
ArgIn, ArgOut and ArgInOut are set to the input/output parameters specified by the stored procedure
If none are specified, enter _DBC_Unused
The results of the stored procedure are output to ReturnVal and ResultSet

FAQ
What is a stored procedure?
A set of processing stored in the database.
How is it different from executing SQL statements directly from the PLC?
Complex processing can be moved to the database side, improving maintainability.
Can input parameters be passed?
Yes, using the ArgIn parameter.
Can return values be obtained?
Yes, with ReturnVal and ResultSet.
