SQL Server Join stored procedure result with query

vof42yt1  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(111)

I have a stored procedure that contains a dynamic SQL query that passes a FormId to it and it returns its columns and their values.

Each form has different columns quantity and value so I can't make a temp table and pass the stored procedure result to it.

How can I join this stored procedure result with the rest of my SQL query?

This is my stored procedure:

declare @FormId tinyint = 1
declare @columns as varchar(max) = (select string_agg(quotename(ColumnName), ',') 
                                    from Paint_Form as f 
                                    inner join Paint_FormColumn as fc on fc.FormId = f.FormId 
                                    where f.FormId = @FormId)

declare @sql nvarchar(max) = '

select * 
from 
    (select 
         f.FormId,
         fc.ColumnName,
         fce.CellValue
     from  
         Paint_Form as f 
     inner join 
         Paint_FormColumn as fc on fc.FormId = f.FormId
     inner join 
         Paint_FormCell as fce on fce.ColumnId = fc.ColumnId
     where 
         f.FormId = ' + CONVERT(VARCHAR(4), @FormId) + ') t
pivot
(
    max(CellValue) for ColumnName in (' + @columns + ')
) p
'

exec (@sql)

And I want something like this:

select * 
from report 
left join storedProcedure on formid

My tables: enter image description here

irlmq6kh

irlmq6kh1#

You can join only tables that are base table (containing data) or view. In SQL Server you have two type of views : basic view that needs a CREATE TABLE STATEMENT and parametric view that is an inline table function (UDF).

Stored procedures can return datasets. Datasets arn't tables. So you cannot use the name of a stored procedure to put it into the FROM clause of a query...

You have 2 possibilities for a workaround :

  • acting outside the SP scope by creating a tamporary table, then insert the exec of the SP into, then use it in your final query
  • acting inside the SP scope by adding the final query logic into the code of your SP

But I will certainly never do the first solution nor the second one and acquiesce to all the remarks that have been done like using views (without SCHEMABINDING) PIVOT operator if necessary...

相关问题