Assume we have two users in our database tenant1
and tenant2
with their own schemas (also called tenant1
and tenant2
).
We create a Contacts
table for each tenant so we have tenant1.Contacts
and tenant2.Contacts
.
Within our application we execute the following SQL using Dapper. We are using a tenant specific connection string that uses the tenant's SQL Server login details.
select * from Contacts
Since we did not specify the schema within the SQL it is inferred from the default schema of the user under which the SQL executed. So for tenant1
it will query tenant1.Contacts
and for tenant2
it will query tenant2.Contacts
.
Now we'll create a stored procedure in the dbo
schema that executes the same query:
CREATE PROCEDURE GetContacts
AS
BEGIN
select * from Contacts
END
GO
Note that I've not specified a schema in the Stored Procedure's SQL.
When we execute the stored procedure from our application the schema of the stored procedure can still be inferred from the current user but the SQL within the SP infers the schema from that of the SP. So if the SP belongs to the dbo
schema it will execute the query against the dbo.Contacts
table.
This is what is happening in your situation. You have created a stored procedure in the dbo
schema and expecting it to execute the SQL against the tenant's default schema.
You have a few options
- Pass the schema to your stored procedure as a parameter and use dynamic SQL - How to pass schema as parameter to a stored procedure in sql server?
- Create a version of the SP for each tenant e.g.
tenant1.SP_Name
,tenant2.SP_Name
- Don't use stored procedures.