Reputation: 514
I have a stored procedure SprocA resides on ServerA. SprocA takes 4 parameters, executes a dynamic sql and returns a record with 1 column (1 integer value). I'd like to be able to call this from a function FnB on ServerB so that I can use it in a stored procedure SprocB on server ServerB to return a recordset.
For example, I'd like to have something like this
Create Function FnB
@CustomerId int
,@PartId varchar(30)
,@DateFrom datetime
,@DateTo datetime
Returns int
As
Begin
Declare @Ret int
Exec @Ret = LnkSrv.DB_History.dbo.SprocA(@CustomerId, @PartId, @DateFrom, @DateTo)
Return @Ret
End --FnB
Create Procedure SprocB
@RowId int
As
Begin
Select Partid, FnB(Customerid, Partid, DateFrom, DateTo) As TotalQtyShipped
, AskedPrice, AskedQty, AppvPrice, AppvQty
From Tbl_Header a
Inner Join Tbl_Detail b On a.RowID = b.RowID
Where a.RowID = @RowId
End --SprocB
Possible result:
PartID TotalQtyShipped AskedPrice AskedQty AppvPrice AppQty
pn1 1000 10 100 10 100
pn2 550 20 50 15 50
pn3 2000 5 2000 5 1500
Please help
TL
Upvotes: 0
Views: 108
Reputation: 7979
If your solution based on dynamic SQL (ServerA.SprocA) you can't use functions at all in the following call sequence because SQL Server treats functions as deterministic and you can't change SQL Server state in the function call.
if I were on your place I'd made that LnkSrv.DB_History.dbo.SprocA creates denormalized table (tbl_FnB) with following (see below) columns insted of returning scalar value
CustomerId PartId DateFrom DateTo TotalQtyShipped
then SprocB would look like this
Create Procedure SprocB
@RowId int
As
Begin
exec LnkSrv.DB_History.dbo.SprocA; -- creates table Tbl_FnB on its side
Select Partid, Tbl.TotalQtyShipped
, AskedPrice, AskedQty, AppvPrice, AppvQty
From Tbl_Header a
Inner Join Tbl_Detail b On a.RowID = b.RowID
Inner Join LnkSrv.DB_History.dbo.Tbl_FnB f On f.CustomerId = b.Customerid
and f.Partid = b.Partid
and f.DateFrom = b.DateFrom
and f.DateTo = b.DateTo
Where a.RowID = @RowId
End --SprocB
I assumed that fields CustomerId PartId DateFrom DateTo
located in the Tbl_Detail table
Upvotes: 1
Reputation: 2006
There's no real issue with what you're asking for except that you cannot use execute inside a function as you have it;
You can however do this:
create proc [dbo].[GetRowCount] (@TblName NVARCHAR(25) , @Itemid INT,@RowCnt int = 0)
AS BEGIN
DECLARE @Sqlstring nvarchar(2000)
set @Sqlstring = 'SELECT @RowCnt = COUNT(*) FROM ['+ @TblName +']
WHERE Itemid = '+ convert(varchar(10),@Itemid)
EXEC sp_executesql @Sqlstring,N'@RowCnt int output',@RowCnt output
END
...
declare @RowCnt int
exec [GetRowCount] @TblName='TableName',@Itemid='ItemID',@RowCnt=@RowCnt output
select @RowCnt
you should be able to adapt this for your own situation.
Upvotes: 0