views:

277

answers:

2

This is making me nuts and I'm sure the answer is SO easy.

I have multiple schemas that each have a view named "Task". I want to make a single stored proc that users running in multiple default schemas can execute successfully -- that stored proc does a select on the Task view.

So say I have these objects:

View: fr.Task (users with default schema of 'fr' get this if they just type "select * from Task" View: de.Task (ditto, but for users with default schema of 'de')

StoredProc: dbo.MyProc -- all users have execute permissions. The proc is simply:

select count(*) from Task

Now I would expect (and I want) that if a user with default schema 'fr' did

exec dbo.MyProc

Then they would get the count of rows from view fr.Task. But instead they get error "Invalid object name 'Task'."

Is it not possible to make a generic storedproc that will execute a select in the schema of the running user?

Thx, Bill

+3  A: 

To run a stored procedure in the context of the CALLER you can use the Execute As clause however, I suspect that this is not really what you are wanting to do.

http://msdn.microsoft.com/en-us/library/ms188354.aspx

John Sansom
Reading the details of Execute As, it seems like it's exactly what I want. Interestingly, however, it didn't work. I re-created the stored proc with the "WITH EXECUTE AS CALLER", but still get the same error. Bummer.
BillVienna
Run, SELECT CURRENT_USER, within your stored procedure to validate who the caller is.
John Sansom
Good idea. It returns the correct (non-dbo) caller, the one that I was hoping for. Therefore the problem is not that it's failing to run in the context that I want, but rather it does not resolve the view name "Task" without a schema prefix. That's a bummer, because the whole point was to have just one stored proc that multiple users (with multiple default schemas) could call, and the stored proc would automagically reference objects in the default schema of the caller. But it looks like it doesn't work that way.
BillVienna
Precisely, schemas are intended as a security feature rather than a means to resolve an object location. Hence, I do not believe they can be used to achieve what you are looking to do unfortunately.
John Sansom
I don't know the answer to this question but suspect that a definitive answer might be found from http://blogs.msdn.com/sqlprogrammability/archive/2006/04/03/567643.aspxIt says: "This series of blogs describe name resolution behavior of schema objects, types and XML schema collections, and how it interacts with default schema, compile plan implicit schema."
Paul Harrington
A: 

Use Dynamic SQL ie., exec ('select count(*) from Task')

Ganesan Krishnan