Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server creating wrong table names, why?

Question: when I create a table (T_TableName) using SQL Server Management-Studio, it always creates the table as

Domain\UserName.T_TableName

instead of

dbo.T_TableName

What's wrong ?

like image 987
Stefan Steiger Avatar asked Feb 19 '10 09:02

Stefan Steiger


People also ask

What are the rules for naming a table in SQL?

The rules for naming database objects (such as tables, columns, views, and database procedures) are as follows: Names can contain only alphanumeric characters and must begin with an alphabetic character or an underscore (_). Database names must begin with an alphabetic character, and cannot begin with an underscore.

Why does SQL say invalid object name?

This typically means 1 of 2 things... you've referenced an object (table, trigger, stored procedure,etc) that doesn't actually exist (i.e., you executed a query to update a table, and that table doesn't exist). Or, the table exists, but you didn't reference it correctly...

Can tables have the same name?

To answer your original question, you can't have two objects of the same or similar types (e.g., two tables, or a table and a view) with the same name in the same schema.


1 Answers

If you don't specify a schema explicitly on your table name to be created, it will be created in the user's current default schema.

I bet the user you're using has its own personal schema set as its default schema - that's why your tables get created in his own personal schema.

You can check what database users you have and what their default schema is by inspecting sys.database_principals (SQL Server 2005 and up):

SELECT name, type_desc, default_schema_name
FROM sys.database_principals

To solve this:

  • specify the schema you want to use explicitly (best practice anyway!)

    CREATE TABLE dbo.T_TableName
    
  • change the user's default schema to dbo

    ALTER USER [Domain\YourUser] WITH DEFAULT_SCHEMA = dbo
    

But as a general rule of thumb, I recommend always using the "dbo." prefix explicitly, if you want to have all your database objects in the dbo schema. Helps with performance, too (ever so slightly) since SQL Server won't have to go hunting in different schemas, if you explicitly tell it where your db objects live.

like image 194
marc_s Avatar answered Oct 14 '22 06:10

marc_s