Перейти к содержимому

Dbo sql server что это

  • автор:

What is dbo in SQL Server?

I used to learn about SQL, especially MySQL. Then now my job requires me to understand Microsoft SQL Server (mssql). So I make these notes to guide me and others who want to transition to mssql. I usually summarized what I found and understood so far from browsing the internet.

dbo stands for DataBase Owner.

We can’t remove privileges from an object owner and we can’t drop users from a database if they own objects in it.

AdventureWorks database

schema is a named container for database objects, which allows us to group objects into separate namespaces. The schema is the database object that owns the table. For example, the AdventureWorks sample database contains schemas for Production, Sales, and HumanResources.

The four-part naming syntax for referring to objects specifies the schema name.

Exit fullscreen mode

Schemas can be owned by any database principal and a single principal can own multiple schemas. Principals are entities that can request SQL Server resources.

Schemas that contain objects cannot be dropped. The following schemas cannot be dropped: dbo , guest , sys , INFORMATION_SCHEMA .

The sys and INFORMATION_SCHEMA schemas are reserved for system objects. We cannot create objects in these schemas and we cannot drop them.

user-schema-object

The dbo schema is the default schema of every database for all users. By default, users created with the CREATE USER Transact-SQL command have dbo as their default schema. The dbo schema is owned by the dbo user account.

For example, the name of a table called orders owned by dbo is dbo.orders . If the table’s ownership is transferred to user abc , the table will now be named abc.orders .

Users who are assigned the dbo as default schema don’t inherit the permissions of the dbo user account. No permissions are inherited from a schema by users; schema permissions are inherited by the database objects contained in the schema.

the dbo user account is not the same as the db_owner fixed database role and the db_owner fixed database role is not the same as the user account that is recorded as the owner of the database.

The default schema for a user is solely used for object-reference in case the user omits the schema when querying objects. Users in the database will be able to access any object owned by dbo without specifying the owner as long as the user has appropriate permission.

Why do table names in SQL Server start with "dbo"?

At least on my local instance, when I create tables, they are all prefixed with «dbo.». Why is that?

AakashM's user avatar

6 Answers 6

dbo is the default schema in SQL Server. You can create your own schemas to allow you to better manage your object namespace.

If you are using Sql Server Management Studio, you can create your own schema by browsing to Databases — Your Database — Security — Schemas.

To create one using a script is as easy as (for example):

You can use them to logically group your tables, for example by creating a schema for «Financial» information and another for «Personal» data. Your tables would then display as:

Financial.BankAccounts Financial.Transactions Personal.Address

Rather than using the default schema of dbo.

Fenton's user avatar

Microsoft introduced schema in version 2005. For those who didn’t know about schema, and those who didn’t care, objects were put into a default schema dbo .

dbo stands for DataBase Owner, but that’s not really important.

Think of a schema as you would a folder for files:

  • You don’t need to refer to the schema if the object is in the same or default schema
  • You can reference an object in a different schema by using the schema as a prefix, the way you can reference a file in a different folder.
  • You can’t have two objects with the same name in a single schema, but you can in different schema
  • Using schema can help you to organise a larger number of objects
  • Schema can also be assigned to particular users and roles, so you can control access to who can do what.

You can generally access any object from any schema. However, it is possible to control which users have which access to particular schema, so you can use schema in your security model.

Because dbo is the default, you normally don’t need to specify it within a single database:

mean the same thing.

I am inclined to disagree with the notion of always using the dbo. prefix, since the more you clutter your code with unnecessary detail, the harder it is to read and manage.

For the most part, you can ignore the schema. However, the schema will make itself apparent in the following situations:

If you view the tables in either the object navigator or in an external application, such as Microsoft Excel or Access, you will see the dbo. prefix. You can still ignore it.

If you reference a table in another database, you will need its full name in the form database.schema.table :

For historical reasons, if you write a user defined scalar function, you will need to call it with the schema prefix:

This does not apply to other objects, such as table functions, procedures and views.

You can use schema to overcome naming conflicts. For example, if every user has a personal schema, they can create additional objects without having to fight with other users over the name.

What’s dbo?

Don’t you hate it how certain words (well, acronyms in this case) get reused to mean multiple things? dbo seems to cause a great deal of confusion because of this.

First, dbo is an acronym standing for DataBase Owner. And there are three common usages for that I can think of off the top of my head. Feel free to point out others in the comments below and I’ll add them to the list ��

The actual owner of the database.

When talking about permissions this is the actual dbo. There is only one and they can’t be denied and they can do pretty much anything they want in the database.

Members of/have the permissions of the db_owner role.

“She’s dbo.” “He’s a member of dbo.” etc. This is a colloquial use of the term and isn’t technically accurate. The database owner (dbo) is not quite the same as the role db_owner. I generally prefer the more accurate terms (db_owner over dbo) but even I make mistakes here sometimes.

These first two are really not all that different. I’ve seen it create a little bit of confusion every now and again but not often and not much.

The schema.

This is where people start having difficulties. The schema dbo is the most commonly seen usage but it does not have anything to do with permissions. Schemas are containers that hold the objects within a database. They are third part of a fully defined four-part name (InstanceName.DatabaseName.SchemaName.ObjectName). The dbo schema is no different from the schema Sales. Well, other than the fact that most objects in almost every database are put in the dbo schema and I rarely see the Sales schema outside of AdventureWorks databases. Effectively though, they are both just schemas. The owner of the dbo schema has a lot of power, but only because so many objects are in that schema. If you create a database with a schema named Sales and put all of the objects under that schema rather than dbo then the owner of Sales has more power than the owner of dbo.

Obviously the difference between the permissions dbo and the schema dbo is pretty significant. In the end, you’ll have to use context to figure out which dbo you are working with, and if you aren’t sure then you need to look closer and/or ask questions.

Dbo sql server что это

При создании любой базы данных в ней автоматически создаются четыре специальных пользователя:

q dbo (от database owner ) — пользователь-владелец базы данных. Он автоматически создается для того логина, от имени которого была создана эта база данных. Конечно же, как владелец, он получает полные права на свою базу данных (при помощи встроенной роли базы данных db_owner ). В SQL Server 2005 (в отличие от предыдущих версий) dbo может удалить свою базу данных;

q guest (гость) — этот специальный пользователь предназначен для предоставления разрешений всем логинам, которым не соответствует ни один пользователь в базе данных. По умолчанию у этого пользователя нет права login для базы данных, и, следовательно, работать он не будет. Этот пользователь используется чаще всего для предоставления разрешений логинам на какие-то учебные/тестовые базы данных или на базы данных-справочники, доступные только на чтение;

q INFORMATION_SCHEMA — этому пользователю не может соответствовать ни один логин. Его единственное значение — быть владельцем схемы INFORMATION_SCHEMA , в которой хранятся представления системной информации для базы данных;

q sys — этому специальному пользователю, как и INFORMATION_SCHEMA , не могут соответствовать логины. Он является владельцем схемы SYS , к которой принадлежат системные объекты базы данных.

Всем доброго дня. С MS SQL Server раньше не работал, недавно пришлось столкнуться по работе, необходимо выполнить одну служебную задачу, но наткнулся на некую странность, был бы очень признателен знатокам за ответ почему так происходит или совет, где про это почитать. Уверен что я просто чего-то не понимаю.

Описание:

Установлен MS SQL Server 2012. Имеется база данных предположим называется Сompany. В базе данных имеется одна схема dbo, все таблицы базы данных принадлежат этой схеме, например:

dbo.People

dbo.Products

dbo.Сars

Открываю SQL Management Studio и подключаюсь к серверу СУБД используя доменную авторизацию, например CORPIvanov.

Далее если выполнить создание таблицы с помощью команды CREATE TABLE:

то все хорошо, создается таблица привязанная к схеме dbo:

dbo.departaments

Но если выполнить создание таблицы с помощью SELECT INTO:

то таблица создается и появляется новая схема, имя которой совпадает с доменным именем CORPIvanov, т.е. таблица представлена в дереве объектов как:

CORPIvanov.departaments

Вопрос:

С чем связано такое поведение?

Примечание:

Я в курсе, что если указать схему dbo при создании таблицы, то таблица создается в этой схеме:

Но интересует именно вариант без ее указания.

Основным принципом безопасности SQL Server является то, что владельцы объектов имеют неотзываемые разрешения на их администрирование. A core concept of SQL Server security is that owners of objects have irrevocable permissions to administer them. Нельзя удалять права доступа у владельцев объектов. Также нельзя удалять пользователей из базы данных, если они владеют в ней объектами. You cannot remove privileges from an object owner, and you cannot drop users from a database if they own objects in it.

Отделение пользователей от схем User-Schema Separation

Отделение пользователей от схем обеспечивает дополнительную гибкость в управлении разрешениями объектов базы данных. User-schema separation allows for more flexibility in managing database object permissions. Схема — это именованный контейнер для объектов базы данных, который позволяет группировать объекты в отдельные пространства имен. A schema is a named container for database objects, which allows you to group objects into separate namespaces. Например, образец базы данных AdventureWorks содержит схемы для Production, Sales и HumanResources. For example, the AdventureWorks sample database contains schemas for Production, Sales, and HumanResources.

Четырехкомпонентный синтаксис ссылок на объекты указывает имя схемы. The four-part naming syntax for referring to objects specifies the schema name.

Владельцы схемы и разрешения Schema Owners and Permissions

Владельцем схемы может быть любой участник базы данных, при этом одному участнику может принадлежать несколько схем. Schemas can be owned by any database principal, and a single principal can own multiple schemas. К схеме можно применить правила безопасности, которые наследуются всеми объектами схемы. You can apply security rules to a schema, which are inherited by all objects in the schema. После установки разрешений доступа для схемы они автоматически применяются по мере добавления к схеме новых объектов. Once you set up access permissions for a schema, those permissions are automatically applied as new objects are added to the schema. Пользователь может назначить новую схему, а несколько пользователей базы данных могут совместно использовать одну одну схему. Users can be assigned a default schema, and multiple database users can share the same schema.

По умолчанию, если разработчик создает объект в схеме, он принадлежит участнику безопасности, являющемуся владельцем схемы, а не разработчику. By default, when developers create objects in a schema, the objects are owned by the security principal that owns the schema, not the developer. Владение объектом можно передать с помощью инструкции Transact-SQL ALTER AUTHORIZATION. Object ownership can be transferred with ALTER AUTHORIZATION Transact-SQL statement. Схема может также содержать объекты, принадлежащие другим пользователям и иметь более детализированные разрешения, чем назначенные схеме, хотя это не рекомендуется из-за увеличения сложности управления разрешениями. A schema can also contain objects that are owned by different users and have more granular permissions than those assigned to the schema, although this is not recommended because it adds complexity to managing permissions. Объекты можно перемещать из одной схемы в другую, а принадлежность схемы передавать от одного участника другому. Objects can be moved between schemas, and schema ownership can be transferred between principals. Пользователей базы данных можно удалять, не влияя этим на схемы. Database users can be dropped without affecting schemas.

Встроенные схемы Built-In Schemas

SQL Server поставляется с десятью предварительно определенными схемами, имеющими одинаковое имя со встроенными пользователями и ролями базы данных. SQL Server ships with ten pre-defined schemas that have the same names as the built-in database users and roles. Они существуют главным образом ради обратной совместимости. These exist mainly for backward compatibility. Схемы, имеющие одинаковые имена с предопределенными ролями базы данных, можно удалить, если они не нужны. You can drop the schemas that have the same names as the fixed database roles if you do not need them. Нельзя удалить следующие схемы. You cannot drop the following schemas:

Если их удалить из шаблона базы данных, эти схемы не появятся в новых базах данных. If you drop them from the model database, they will not appear in new databases.

Схемы sys и INFORMATION_SCHEMA зарезервированы для системных объектов. The sys and INFORMATION_SCHEMA schemas are reserved for system objects. В этих схемах нельзя создавать и удалять объекты. You cannot create objects in these schemas and you cannot drop them.

Схема dbo The dbo Schema

Схема dbo представляет собой схему по умолчанию для вновь созданной базы данных. The dbo schema is the default schema for a newly created database. Владельцем схемы dbo является учетная запись пользователя dbo . The dbo schema is owned by the dbo user account. Схемой по умолчанию для пользователей, созданных с помощью команды Transact-SQL CREATE USER, является dbo . By default, users created with the CREATE USER Transact-SQL command have dbo as their default schema.

Пользователи, которым назначена схема dbo , не наследуют разрешения пользовательской учетной записи dbo . Users who are assigned the dbo schema do not inherit the permissions of the dbo user account. Пользователи не наследуют разрешения схемы, их наследуют объекты базы данных, содержащиеся в схеме. No permissions are inherited from a schema by users; schema permissions are inherited by the database objects contained in the schema.

Если на объект базы данных ссылаются с помощью однокомпонентного имени, SQL Server вначале ищет этот объект в схеме пользователя по умолчанию. When database objects are referenced by using a one-part name, SQL Server first looks in the user’s default schema. Если объект не найден, SQL Server ищет его в схеме dbo . If the object is not found there, SQL Server looks next in the dbo schema. Если этот объект не найден в схеме dbo , возвращается ошибка. If the object is not in the dbo schema, an error is returned.

Внешние ресурсы External Resources

Дополнительные сведения о принадлежности объектов и схемах см. в следующих документах. For more information on object ownership and schemas, see the following resources.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Car Rental HPN Inside the Terminal