Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stored procedure calling data in a different schema

SQL Server 2008 R2: normally, we create our table, and stored procedure, and grant a user execute rights to the stored procedure. We never have to grant specific rights to the tables or views because if they user can execute the stored procedure SQL Server infers that the stored procedure should be allowed to perform the select/insert/update statements. Works well because we're only dealing with one schema, but now we've got a scenario where the tables are in one schema, but a stored procedure is in another. When the user executes the stored procedure, they get an error:

Msg 229, Level 14, State 5, Procedure teststoredprocedure, Line 7 The SELECT permission was denied on the object 'testtable', database 'testdatabase', schema 'testschema'.

teststoredprocedure is in a different schema than testtable. Is it possible to allow the stored procedure to select from tables, without granting the user specific rights to those tables?

like image 996
Jeremy Avatar asked Dec 14 '11 20:12

Jeremy


People also ask

Can I call a stored procedure from another?

In releases earlier than SQL Server 2000, you can call one stored procedure from another and return a set of records by creating a temporary table into which the called stored procedure (B) can insert its results or by exploring the use of CURSOR variables.

Are stored procedures part of the schema?

Stored Procedures and Functions A procedure or function is a schema object that logically groups a set of SQL and other PL/SQL programming language statements together to perform a specific task. Procedures and functions are created in a user's schema and stored in a database for continued use.

Can a trigger and procedure have the same name in the same schema?

If you are not using (or even familiar with) schemas then the short answer is no. Object names within a schema must be unique, so if you only have the one (default) schema then object names must be unique full stop. Save this answer.


1 Answers

You need to give the owner of the stored procedure WITH GRANT access to the table.

Generally a Schema is owned by a Role with the same name as the schema, so to allow storedprocschema.teststoredprocedure to access the table it would be:

GRANT SELECT on testschema.testtable TO storedprocschema WITH GRANT

This should work IF and only if the table is in the same database as the proc.

To achieve the same result with a table in a different database you can either:

  • Enable "Cross Database Ownership Chaining"

  • Move the procedure to the other database, and have a shim procedure in the original database which calls it. Then manage permissions on both procedures.

like image 87
Ben Avatar answered Nov 15 '22 05:11

Ben