Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL server schema and default schema

I have a schema define in my database. Except now everytime I do a sql statement I have to provide the schema ... SELECT * FROM [myschema].table

I set the default schema for my user using management studio and also ran the ALTER USER myUser WITH DEFAULT_SCHEMA [myschema] and I still get the invalid object 'table' when writing a query without the schema (SELECT * FROM table)

Is there a way to write SELECT * FROM table without having to specify the schema name all the time?

It's on SQL 2005 using SQL Management Studio.

like image 268
pdiddy Avatar asked Sep 27 '10 17:09

pdiddy


People also ask

How do I find the default schema in SQL Server?

SELECT SCHEMA_NAME(); The SCHEMA_NAME() function will return the name of a schema if you pass it the schema_id but if you don't pass anything, it will return the name of the current default schema.

What is SQL Server schema?

What is Schema in SQL? In a SQL database, a schema is a list of logical structures of data. A database user owns the schema, which has the same name as the database manager. As of SQL Server 2005, a schema is an individual entity (container of objects) distinct from the user who constructs the object.

What are the 3 types of database schema?

Schema is of three types: Logical Schema, Physical Schema and view Schema.

Why schema is used in SQL?

SQL Server schemas provide the following benefits: Provides more flexibility and control for managing database objects in logical groups. Allows you to move objects among different schemas quickly. Enables you to manage object security on the schema level.


2 Answers

Is the user an SA, if so it will not work, according to the documentation SA users are always defaulted to the dbo schema.

The value of DEFAULT_SCHEMA is ignored if the user is a member of the sysadmin fixed server role. All members of the sysadmin fixed server role have a default schema of dbo.

like image 115
Dustin Laine Avatar answered Oct 07 '22 05:10

Dustin Laine


Couple of options:

  1. Is your user listed under Security > Users (in SSMS)? Check the Properties (right click the name), and see if the Default schema is set in the context of the database, rather than the instance (which is what ALTER USER is setting).
  2. Create a synonym for the table you want to reference:

    CREATE SYNONYM table_name      FOR [your_db].[your_schema].table_name 

    ...which will affect everyone who doesn't use at least two name notation, in the context of that database. Read more about it here. But it is associated ultimately to a schema.

  3. Check that the database selected in the "Available Databases" drop down (upper left, to the left of the Execute button) is correct.

  4. Use three name notation when specifying table (and view) references:

    SELECT *    FROM [your_db].[your_schema].table_name 
like image 21
OMG Ponies Avatar answered Oct 07 '22 03:10

OMG Ponies