I want to access outside the scope of a stored procedure a table variable that it defines. I have tried this one, but my case is different because my procedure receives a varchar
as a parameter and then it creates a varchar
that is executed, someway like this:
create procedure p_x
@Table varchar(250)
as
begin
declare @Sql varchar(450)
select @sql = 'declare ' + @Table + 'table(col1 varchar(10), col2 float, col3 float, col4 float)'
select @sql = @sql + ' insert' + @Table + ' values('a', 1,1,1)'
select @sql = @sql + ' insert' + @Table + ' values('b', 2,2,2)'
select @sql = @sql + ' select * from'
execute(@sql)
end
go
The solution the other question does is to pass as a parameter the new table to be processed. But in my case, because the code is written in a decisive part inside a varchar
concatenation (and also it creates auxiliary tables concatenating at the end of the varchar @Table
), I don't know what to do.
To give some context: there is this procedure that uses global temporary tables, which were called inside queries. Everything was working fine until we need to change the query to transform it into a table-valued function. The query just access the tables defined inside the procedure through global scope, but the table-valued function doesn't allow to access these global temporary tables. It seems that table variables can't be global.
In short, to change the query to a table-valued function, I need to change the procedure's temporary tables into table variables that I can access inside the table-valued function.
The big picture: 1) Today I have a query that works and this query calls a procedure.
2) I want to be able to call this query from a API without having to paste 100 lines of query
3) I received the suggestion of converting the query into a TFV
4) I did it, but it doesn't work, because TFV can't use temporary tables
5) I want a workaround to create a copy of the procedure with some minor changes that I can call from the TVF.