Reputation: 19
I am attempting to query data from our Oracle server via our SQL server. To perform this in a thin-client manner, I am using OpenQuery. I would like to build a single table-based function that can be used to query various linked tables as needed. I can't quite figure out the syntax to make this work. Here is what I have so far. Any help is greatly appreciated!
CREATE FUNCTION [dbo].[fnTEST](
@Table varchar (100),
@Fields varchar (1000),
@Condition varchar(5000)
)
RETURNS
@TEST TABLE()
AS
BEGIN
DECLARE @OPENQUERY nvarchar(4000);
DECLARE @TSQL nvarchar(4000);
SET @OPENQUERY = 'SELECT * FROM OPENQUERY([TEST-Link],'''
SET @TSQL = 'SELECT ' + @Fields + ' FROM TEST.' + @Table + ' WHERE ' + @Condition + ''')'
EXEC (@OPENQUERY+@TSQL)
END;
The error I am currently getting is:
Msg 102, Level 15, State 1, Procedure fnTEST, Line 12 [Batch Start Line 7]
Incorrect syntax near ')'.
Highlighted at @TEST TABLE()
Upvotes: 1
Views: 718
Reputation: 56725
This is all not recommended for a number of reasons, but here the big one is that, as indicated in the MS doc, you cannot use dynamic SQL from a user-defined function:
...
User-defined functions cannot make use of dynamic SQL or temp tables. Table variables are allowed.
...
Here are some of the other problems with this approach:
The way that I would do something link this is as follows:
Define the explicit queries/datasets that your app needs from the Oracle Database.
Write those queries as stored procedures, on the Oracle database.
Setup a Linked Server definition in your SQL Server database to the Oracle database. Configure the security for each side appropriately.
Write specific stored procedures on your SQL Server to call the corresponding procedures in the Oracle database. Use remote EXEC's to do this through the Linked Server definition.
(NOTE: Remote EXEC execution is done with the AT <linkedServer>
clause).
Upvotes: 1
Reputation: 89006
Enable the linked server for rpc out
and simplify this to
EXEC (@sql) at [TEST-Link]
Upvotes: 0