Search code examples
phpsql-serversqlsrvcross-database

Is it possible to execute a stored procedure and function with a cross-database query via php/sqlsrv?


I am working with a database that must not be modified by our code and another database on the same server set up specifically to fascilitate our needs in that regard. Some uses of the latter (let's call it db2) depend on keeping db2 up to date with (what we'll call) db1, which is mostly handled through scheduled jobs with stored procedures on db2 which use functions also on db2. For a simplified example,

INSERT INTO [db2].[dbo].[lateitems] (orderid, description, originalduedate)
    SELECT      orderid,
                description,
                originalduedate
    FROM        ha_lateorders() lo
    WHERE       NOT EXISTS (SELECT  orderid
                            FROM    [db2].[dbo].[lateitems] li
                            WHERE   li.orderid = lo.orderid;

Which calls a function like,

    SELECT      orderid,
                description,
                originalduedate
    FROM        [db1].[dbo].[orderitems] oi
    WHERE       originalduedate < GETDATE()
    AND         originalduedate > DATEADD(week, -1, GETDATE())

(The actual queries are more complex but these snippets demonstrate where the cross-database query takes place.)

It would be beneficial to call one such stored procedure each time one of our php pages accesses [db2].[dbo].[lateitems], but I don't currently know how to set up to run the lateorders function, with its cross-database query, from a php connection to db2. Is it possibly and, if so, how?

This is a SQL Server database, accessed with php8/sqlsrv.

I have tried to identify necessary user permissions, but so far any attempt to execute that function from php has failed. The same user can successfully run the procedure and function when directly logged into the database.


Solution

  • Never mind, I found the solution. Thought I should add it here for anyone who trips over this in future.

    It was actually a simple oversight. We had not granted SELECT permission on one of the tables in db1.

    Let that be a lesson to me, to always check permissions first!