How can I join on a stored procedure?

后端 未结 9 2046
渐次进展
渐次进展 2020-12-25 10:48

I have a stored procedure that takes no parameters, and it returns two fields. The stored procedure sums up all transactions that are applied to a tenant, and it returns the

相关标签:
9条回答
  • 2020-12-25 11:44

    Your stored procedure could easily be used as a view instead. Then you can join it on to anything else you need.

    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
    

    The you can do any statement like:

    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
    
    0 讨论(0)
  • 2020-12-25 11:45

    insert the result of the SP into a temp table, then join:

    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
    ...
    
    0 讨论(0)
  • 2020-12-25 11:47

    I actually like the previous answer (don't use the SP), but if you're tied to the SP itself for some reason, you could use it to populate a temp table, and then join on the temp table. Note that you're going to cost yourself some additional overhead there, but it's the only way I can think of to use the actual stored proc.

    Again, you may be better off in-lining the query from the SP into the original query.

    0 讨论(0)
提交回复
热议问题