Tuesday, October 17, 2006

Accessing a table in SQL Server 2005 (Schema related)

Recently in a discussion forum I came across this question "I have a small Doubt in SQL server. The database name is 'AdventureWorks' and the table name is 'Production.Culture'. What is the query to fetch records from that table."

The answer to this is :

Select cultureid, [name], modifiedDate from AdventureWorks.Production.Culture

There was another member of the forum who was saying that we need to only use the below query:

Select * from AdventureWorks.dbo.Production.Culture

Please note that he has mentioned two Schema names (dbo and Production) in a single query. This query wouldn't work and I thought I would explain the concept of "Schemas" in SQL Server 2005 to him.

In short,

a) Schema is similar to Namespaces in .NET
b) It helps in logical grouping of tables.
c) To view all existing schema in a database, for example within AdventureWorksDB ::

1. Open ur SQL Mgmt studio
2. Go to AdventureWorks DB and expand it
3. Expand the Tables

4. Now just observe what you see within that. There would be,

i) few tables which starts with "dbo.",
ii) few tables which starts with "Person."
iii) few tables which starts with "Production." etc.,

Those are all called as "Schema Names".

Other easier way to find this is to, navigate to the "Security" tab of the Database. There we will find a folder by name "Schema". Expand that to see all the Schema names related to that DB.

5. Now click on "New query" button and try this

--- This would work
Select * from person.address

6. Now try this

--- This wouldn't work
Select * from dbo.person.address

7. Just for your confirmation, navigate to someother database in ur query window. For example,
Use Master
Go

--- This would work
Select * from adventureworks.person.address

--- This would work
Select * from adventureworks.dbo.AWBuildVersion

--- This would FAIL
Select * from adventureworks.dbo.person.address

8) That said, by DEFAULT when we create any new table it would be assigned to "dbo." schema.

This you can verify by going to ur SQL Mgmt Studio again, navigate to any database of your choice and create a sample table. Now expand the "Tables" folder to see "dbo.YourTableName" (the table which you have created now).

So the bottomline is when accessing a table name in SQL Server 2005, it shld be done like this:

ServerName.DatabaseName.SchemaName.TableName


Please note that if we want we can create our own schema and then assign the tables to it. Also when a new user is being created we can assign the default schema to them. This merits a separate discussion by itself so would write on it sometime soon.

Technorati tags:

No comments: