¿Cómo puedo unirme a un procedimiento almacenado?


Tengo un procedimiento almacenado que no toma parámetros, y devuelve dos campos. El procedimiento almacenado resume todas las transacciones que se aplican a un inquilino, y devuelve el saldo y el id del inquilino.

Quiero usar el conjunto de registros que devuelve con una consulta, y necesito unir sus resultados en el id del inquilino.

Esta es mi consulta actual:

SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
        u.UnitNumber,
        p.PropertyName
FROM tblTenant t
    LEFT JOIN tblRentalUnit u
    ON t.UnitID = u.ID

    LEFT JOIN tblProperty p
    ON u.PropertyID = p.ID

ORDER BY p.PropertyName, t.CarPlateNumber

El procedimiento almacenado es el siguiente:

SELECT tenant.ID AS TenantID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance FROM tblTenant tenant
    LEFT JOIN tblTransaction trans
    ON tenant.ID = trans.TenantID
    GROUP BY tenant.ID

Me gustaría añadir el saldo de la el procedimiento a ella también.

¿Cómo puedo hacer esto?

Author: Pesto, 2009-05-28

8 answers

En realidad me gusta la respuesta anterior (no use el SP), pero si está atado al SP por alguna razón, podría usarlo para llenar una tabla temporal y luego unirse a la tabla temporal. Tenga en cuenta que usted va a costar algunos gastos adicionales allí, pero es la única manera que puedo pensar en utilizar el proc almacenado real.

De nuevo, puede ser mejor alinear la consulta del SP en la consulta original.

 21
Author: AllenG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-28 14:55:45

Inserte el resultado del SP en una tabla temporal, luego únalo:

CREATE TABLE #Temp (
    TenantID int, 
    TenantBalance int
)

INSERT INTO #Temp
EXEC TheStoredProc

SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
    u.UnitNumber, p.PropertyName
FROM tblTenant t
INNER JOIN #Temp ON t.TenantID = #Temp.TenantID
...
 37
Author: devio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-28 15:03:25

La respuesta corta es "no puedes". Lo que tendrá que hacer es usar una subconsulta o puede convertir su procedimiento almacenado existente en una función de tabla. Crearlo como función dependería de cuán "reutilizable" necesitarías que fuera.

 16
Author: CAbbott,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-28 14:53:03

Su procedimiento almacenado podría usarse fácilmente como una vista en su lugar. Luego puedes unirte a cualquier otra cosa que necesites.

SQL:

CREATE VIEW vwTenantBalance
AS

 SELECT tenant.ID AS TenantID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance 
 FROM tblTenant tenant
 LEFT JOIN tblTransaction trans
 ON tenant.ID = trans.TenantID
 GROUP BY tenant.ID

Puedes hacer cualquier declaración como:

SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, 
    t.Memo, u.UnitNumber, p.PropertyName, TenantBalance
FROM tblTenant t
LEFT JOIN tblRentalUnit u
 ON t.UnitID = u.ID
LEFT JOIN tblProperty p
 ON u.PropertyID = p.ID
LEFT JOIN vwTenantBalance v 
 ON t.ID = v.tenantID
ORDER BY p.PropertyName, t.CarPlateNumber
 9
Author: cjk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-29 07:11:38

Resolví este problema escribiendo una función en lugar de un procedimiento y usando CROSS APPLY en una instrucción SQL. Esta solución funciona en SQL 2005 y versiones posteriores.

Gediminas Bukauskas

 5
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-08-09 10:30:39

Ya se ha respondido, la mejor manera de evitar esto es convertir el Procedimiento Almacenado en una Función SQL o una vista.

La respuesta corta, tal como se mencionó anteriormente, es que no puede UNIRSE directamente a un Procedimiento Almacenado en SQL, no a menos que cree otro procedimiento almacenado o función utilizando la salida del procedimiento almacenado en una tabla temporal y unirse a la tabla temporal, como se explicó anteriormente.

Responderé a esto convirtiendo su Procedimiento almacenado en un SQL función y le mostrará cómo usarlo dentro de una consulta de su elección.

CREATE FUNCTION fnMyFunc()
RETURNS TABLE AS
RETURN 
(
  SELECT tenant.ID AS TenantID, 
       SUM(ISNULL(trans.Amount,0)) AS TenantBalance 
  FROM tblTenant tenant
    LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
  GROUP BY tenant.ID
)

Ahora para usar esa función, en su SQL...

SELECT t.TenantName, 
       t.CarPlateNumber, 
       t.CarColor, 
       t.Sex, 
       t.SSNO, 
       t.Phone, 
       t.Memo,
       u.UnitNumber,
       p.PropertyName
FROM tblTenant t
    LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
    LEFT JOIN tblProperty p ON u.PropertyID = p.ID
    LEFT JOIN dbo.fnMyFunc() AS a
         ON a.TenantID = t.TenantID
ORDER BY p.PropertyName, t.CarPlateNumber

Si desea pasar parámetros a su función desde el SQL anterior, entonces le recomiendo usar CROSS APPLY o CROSS OUTER APPLY.

Lea sobre eso aquí.

Salud

 3
Author: Fandango68,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:24

¡Espero que su procedimiento almacenado no esté haciendo un bucle de cursor!

Si no, tome la consulta de su procedimiento almacenado e integre esa consulta dentro de la consulta que está publicando aquí:

SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
        u.UnitNumber,
        p.PropertyName
        ,dt.TenantBalance
FROM tblTenant t
    LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
    LEFT JOIN tblProperty   p ON u.PropertyID = p.ID
    LEFT JOIN (SELECT ID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance
                   FROM tblTransaction
                   GROUP BY tenant.ID
              ) dt ON t.ID=dt.ID
ORDER BY p.PropertyName, t.CarPlateNumber

Si está haciendo algo más que una consulta en su procedimiento almacenado, cree una tabla temporal y ejecute el procedimiento almacenado en esta tabla temporal y luego únase a ella en su consulta.

create procedure test_proc
as
  select 1 as x, 2 as y
  union select 3,4 
  union select 5,6 
  union select 7,8 
  union select 9,10
  return 0
go 

create table #testing
(
  value1   int
  ,value2  int
)

INSERT INTO #testing
exec test_proc


select
  *
  FROM #testing
 1
Author: KM.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-28 15:05:13

¿Por qué no simplemente realizar el cálculo en su SQL?

SELECT 
  t.TenantName
  , t.CarPlateNumber
  , t.CarColor
  , t.Sex
  , t.SSNO
  , t.Phone
  , t.Memo
  , u.UnitNumber
  , p.PropertyName
  , trans.TenantBalance
FROM tblTenant t
     LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
     LEFT JOIN tblProperty p ON u.PropertyID = p.ID
     INNER JOIN (
       SELECT tenant.ID AS TenantID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance 
       FROM tblTenant tenant
            LEFT JOIN tblTransaction trans ON tenant.ID = trans.TenantID
       GROUP BY tenant.ID
     ) trans ON trans.ID = t.ID
ORDER BY 
  p.PropertyName
  , t.CarPlateNumber
 0
Author: Lieven Keersmaekers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-28 14:55:35