1

Please can any one advise if it is possible to have a stored procedure in the [dbo] schema select data from one table in one schema for users accessing via one database role and for it to select data from a like-named table in another schema for users accessing via another database role?

For example if I have three schemas in my database:

  • dbo
  • green
  • red

I have two database logins [RedLogin] and [GreenLogin]. These connect to my database using respective database users [RedUser] and [GreenUser]. These users are members of the respective database roles [RedRole] and [GreenRole].

  • [RedUser] has a default schema of [red].
  • [GreenUser] has a default schema of [green].
  • [RedRole] has execute permission on [dbo] and select permission on the [red] schema.
  • [GreenRole] has execute permission on [dbo] and select permission on the [green] schema.
  • In the [green] schema I have a table called [User].
  • In the [red] schema I have a table called [User].
  • In the [dbo] schema I have a stored procedure called [User_GetAll] that runs

    SELECT * FROM USER;

What I would like is:

  • For users who login with [Redlogin] and call the [User_GetAll] get all users from the [red].[User] table.
  • For users who login with [Greenlogin] and call the [User_GetAll] get all users from the [green].[User] table.

Is this even possible? If so what is the best way to achieve it, please? Thank you.

Please note: The scenario above is just to get a flavour of what I am trying to achieve. In the real project there are many tables and stored procedures that the solution will need to be applied to.

4

1 回答 1

1

SCHEMA_NAME()如果您使用返回调用者默认架构的方法(http://msdn.microsoft.com/en-gb/library/ms175068.aspx) ,这应该是可能的

所以对于你的例子:

DECLARE @Sql NVARCHAR(MAX)
SET @Sql = 'SELECT * FROM ' + SCHEMA_NAME() + '.USER'
EXEC sp_executesql @Sql

更新:

奇怪的是,当我刚刚做了一个快速测试时,EXEC('SELECT * FROM USER')使用用户默认模式调用它。也许您可以尝试将存储过程的内容包装在一个EXEC('')

例如:

EXEC('
    SELECT * FROM USER
    SELECT * FROM USER
    SELECT * FROM USER
    SELECT * FROM USER
')
于 2014-06-26T12:22:46.957 回答