0

I try to remotely query table-valued function as it is offered in this SO answer.

But I stumbled over how to get the returned result sets to further work with them in sql code...

Calling UDF remotely is not supported by SQL Server and openquery cannot have parameters - only static string.

declare @query nvarchar(max) = 'select * into #workingDays from openquery(LNKDSRV, ''select * from DB.dbo.fxn_getWorkingDays('''''
    + cast(@date1 as nvarchar(max))
    + ''''',''''' 
    + cast(@date2 as nvarchar(max))
    + ''''')'')';
exec sys.sp_executesql @query;

When #workinDays is later queried there is a error 'invalid object name'.

Community
  • 1
  • 1
Pavel Voronin
  • 13,503
  • 7
  • 71
  • 137

1 Answers1

1

You have to define your table before sp_executesql to be available in the session:

Create table #tbl  
declare @query nvarchar(max) = 'insert into #tbl select * from....
exec sys.sp_executesql @query
select * from #tbl

Another option is to use global temp table ##tbl

RAS
  • 3,375
  • 15
  • 24
  • Yes, you are right. I was mistakenly thinking that 'select * into #tempTable' when run with sp_executesql will create temp table in my scope. – Pavel Voronin Dec 18 '14 at 09:12