2

My program creates databases and tables at runtime. My understanding of Schema is it is a conceptual folder for multiple databases and databases tables. So I wrote some meaningless code just to test out what schema would do to my code.

My program use SQL Server Authentication instead of Windows Authentication, and create database and tables under the username of TmpUser instead of sa.

If I create a table by CREATE TABLE TmpTable, I get dbo.TmpTable for table name. If I explicitly type a new schema in CREATE TABLE abc.TmpTable, I then get the following exception because the schema does not exist:

SqlException: The specify schema name either does not exist or you do not have permission to use it

I went into SSMS and manually create a schema by executing CREATE SCHEMA abc. SSMS outputs saying the schema of abc has been successfully created. But in SSMS Object Explorer > Security > I see no Schema name nor anything else named abc.

Where is my Schema? If abc was not created, then why was CREATE SCHEMA abc executed and what did it create?

I went back to Visual Studio and CREATE TABLE abc.TmpTable again, still I receive the same exception.

4

1 回答 1

2

您的 TmpUser 无权访问架构。

选项1

CREATE SCHEMA abc AUTHORIZATION TmpUser;

引自https://docs.microsoft.com/en-us/sql/t-sql/statements/create-schema-transact-sql

“AUTHORIZATION owner_name 指定将拥有架构的数据库级主体的名称。此主体可能拥有其他架构,并且可能不会将当前架构用作其默认架构。”

TmpUser 将拥有架构,因此将有权访问它。

选项 2

显式授予 TmpUser 权限:

GRANT SELECT, UPDATE, DELETE, INSERT SCHEMA abc TO TmpUser;

请参阅https://docs.microsoft.com/en-us/sql/t-sql/statements/grant-schema-permissions-transact-sql上的用法

这就像选项 1,但您可以细粒度的权限。

选项 3

将 TmpUser 赋予一些数据库角色,例如 db_datareader:

USE MyDatabase
GO
ALTER ROLE db_datareader ADD MEMBER TmpUser

TmpUser 将对数据库中的所有模式具有读取权限。

选项 4

它类似于选项 3,但不是使用内置角色,而是创建自己的角色:

USE MyDatabase
GO
CREATE ROLE myrole
GRANT SELECT, DELETE, INSERT, UPDATE, EXECUTE TO myrole
ALTER ROLE myrole ADD MEMBER TmpUser

myrole 中的用户将对数据库中的所有模式具有读/写/执行访问权限。

于 2017-04-26T13:33:48.150 回答