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
1条答案
按热度按时间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 :
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...