Background
I have a procedure stored in a database in SQL Server 2012 1 that averages some values. This stored procedure receives as parameters two (2) values of type int.
Example:
- IdFuntionary
- IdProcess
1 It is the version of the database manager that I have on the development team, but it is possible that this database is installed in a different version.
Problem
Since the stored procedure should also allow to obtain the average of all the officials, I would like to create a new procedure to execute it in this way:
Test query code:
-- Crear tabla temporal. Código adaptado de
-- https://stackoverflow.com/a/654418/4092887
CREATE TABLE #tmpBus
(
IDFUNCIONARIO NUMERIC (12, 0),
NOMBRE VARCHAR(100),
CAL_1 FLOAT,
CAL_2 FLOAT
);
-- Usando CTE "Common Table Expressions", recorrer la tabla "Funcionarios"
-- e invocar el procedimiento almacenado para ir guardando los resultados
-- en la tabla temporal "#tmpBus".
WITH CTE_func
AS
(
SELECT FUNC.IdFuncionario, FUNC.Nombre, 1 AS IdProceso
FROM Funcionario AS FUNC
)
SELECT temp.Nombre, EXEC SP_PromedioReporte temp.IdFuncionario, temp.IdProceso
FROM CTE_func AS temp
-- Retornar los valores almacenados en la tabla temporal.
SELECT *
FROM #tmpBus
Where SP_PromedioReporte
is the crenelated procedure that calculates the average according to the employee and process specified; returning two columns:
---------------------------
| Promedio 1 | Promedio 2 |
---------------------------
The results I hope to obtain are similar to this table:
---------------------------------------
| Nombre | Promedio 1 | Promedio 2 |
---------------------------------------
|Alfonso | 10 | 85 |
---------------------------------------
|María | 12 | 38 |
---------------------------------------
|Jaime | 16 | 63 |
---------------------------------------
|Rodrigo | 20 | 69 |
---------------------------------------
|Laura | 18 | 49 |
---------------------------------------
Looking at other questions and answers in Stack Overflow, I found this answer where basically a temporary table is created to store the results of the stored procedure, but I can not adjust the query so that when traversing all the officials (from the Officers table) , it is executed and saved in the temporary table.
The errors I have are of syntax and I admit that I have no idea how I can perform this functionality.
How can I generate a stored procedure that in turn calls another stored procedure "in this case, at SP_PromedioReporte
" as explained in this question? see test query code: .
NOTE: For this case, I am looking for a solution purely in SQL Server, since, logically, I could first consult the table "Officials" and make a cycle to go calling the stored procedure and process everything "by back-end ", however, in the project in which I am involved, we want all logic to be applied in stored procedures.