Why do I have to query the full path in ssms? - sql-server

I want to query in ssms but I always have to add the specific schema as a prefix, although I have ran the query:
USE (the specific db I wanna use);
GO
What should I do for ssms to bring back only tables from the specific db and schemas while querying?

Within SQL Server, you use the Fully Qualified Name. That consists of three parts (though technically, when using a linked server, you could add a servername part as well):
Database
Schema
Table
And can be used in the following manner:
SELECT * FROM <database>.<schema>.<table>
The USE keyword simply changes the context in which you are executing a SQL command. It's identical to using the drop-down box in SSMS to change to a different database.
By switching the database context, you can typically skip the part of the query above. By switching context, it is assumed all commands will be executed within the database you changed to.
The reason it's still there is if you want to access objects that physically reside within a different database on the same SQL Server instance.
The schema is just a way to group your tables. The default schema is database owner (dbo). If you omit the schema name, it's assumed the object is in the dbo schema. So the following 2 commands are assumed to be identical:
SELECT * FROM dbo.MyTable
SELECT * FROM MyTable
However, using schemas is a great way to structure your database, as you can logically group related objects within the same schema, and assign permissions accordingly.
From an OLTP perspective, you could have a schema dealing with orders, and one with sales. That way it is easier for people to filter only the objects they are interested in, and for the dba to limit access to schemas to specific departments.
If you work with data warehousing, it's not unusual to see an Extract schema, a Stage schema, and a Fact and Dimension schema.

Related

Trying to understand stored procedure behavior

I'm tired of searching for this, but I couldn't find anything.
I have three databases in SQL Server and although all stored procedures are in the Main database, they work with tables from the other databases.
My question is: if you have the query
select name
from SecondDatabase.dbo.SomeTable
where id = 56
and this query is stored in the main database, will it run in the main database and go all the way to the second database and returns the data, or will it run in the second database and you have the select result directly?
(hope you understand my question)
I think you are misunderstanding the difference between a Database and an Instance.
An instance is the software running the SQL service. Each instance can have multiple databases. For example, there is a master database and a tempdb database for each instance of SQL Server, these are system databases. You can create any number of user databases. All these databases will be handled by the same SQL Server instance (on the same machine).
A particular client session is connected first to an instance and then to a particular database, thats why you include which database you will connect to by default on connection strings (or by login). When you write select name from SecondDatabase.dbo.SomeTable, you are telling the SQL service to retrieve data from the SecondDatabase, even if your session is linked to any other database. The engine will then use your login credential to match a user of the other database (since users go by database and logins by instance) to validate if it has enough privileges to query that table, before searching for the data.
A complete different story would be trying to access data from another instance (machine), in which you will need a linked server, a openrowset or such.
use FirstDatabase
select name
from SecondDatabase.dbo.SomeTable
where id = 56
Question:
will it run in the main database and go all the way to the second
database and returns the data, or will it run in the second database
and you have the select result directly?
Your first assumption is correct:
This query will run in a first database, it will use context and all settings (ANSI, query optimizer and statistic related) of the first database but will get data from a table of the second database.
Just an example from a life: if database have to stay in an old compatibility mode, but new T-SQL features need occasionally to be used, query can switch context to tempdb (which normally set to the latest compatibility level) and run queries referencing data from any other database where access is granted. Usage of those new features will not raise exception
The (now edited) query above will always execute on SecondDatabase.dbo.SomeTable even if the active database context was another database and even if the active user had a different default schema. This is because the object SomeTable is qualified with the schema and the schema owner.
Test to illustrate that the following still returns the executed results (assuming the objects exist and the active user context has access to them)
USE [OtherDatabaseSchema]
GO
SELECT TOP 10 *
FROM [SecondDatabase].[dbo].[SomeTable]

How can I divide up my database into different areas for different kinds of information storage in SQL Server?

My database has been created with table names looking like this for the user information:
DROP TABLE [dbo].[webpages_Membership];
DROP TABLE [dbo].[webpages_OAuthMembership];
DROP TABLE [dbo].[webpages_Roles];
DROP TABLE [dbo].[webpages_UsersInRoles];
Is this somewhat of a standard when it comes to table naming conventions? If I now want
to make some new tables would it be reasonable to also name them things like
admin_application
admin_account
or do DBAs normally assign tables used to hold different things to different users when they want to group table types?
I would just like to find out how people normally group tables in an application. Am I
right to assume they are all under one owner in this case dbo or do people leave the
table names alone and have them stored in different owner accounts?
Yes, the best way is to use schemas to divide logically grouped tables. Good example of this is Adventure works database you can download from CodePlex. They have several schemas for different parts of the company such as Person, Production, Purcahsing, Sales and other. See more details on how MS designed this DB.
Have a look at schemas:
create schema webpages authorization dbo;
GO
create table webpages.Membership (...
create table webpages.OAuthMembership (...
create schema admin authorization dbo;
GO
create table admin.application (...
It used to be that before SQL Server 2005, you needed to create a database user in order to create a schema. However, since then, you can create schemas for organizational purposes. Schemas cannot contain schemas, so it's a single level. Schemas can contain any database object, i.e. tables, stored procedures, etc..
Schemas need to have an owner, hence the authorization bit above. Specifying dbo here will make it the same as if you had created it in the dbo schema.

SELECTing across multiple DB2 databases in one query

Ive run into the issue where I need to query 2 separate databases(same instance) in one query.
I am used to doing this with mysql, but Im not sure how to do it with DB2.
In mySQL it would be something like:
SELECT user_info.*, game.*
FROM user_info, second_db.game_stats as game
WHERE user_info.uid = game.uid
So the question is how i translate a query like that into DB2 syntax?
Equivalent of this
Is there a reason why you have the tables in a separate database? MySQL doesn't support the concept of schemas, because in MySQL a "schema" is the same thing as a "database". In DB2, a schema is simply a collection of named objects that lets you group them together.
In DB2, a single database is much closer to an entire MySQL server, as each DB2 database can have multiple schemas. With multiple schemas inside the same database, your query can run more or less unchanged from how it is written.
However, if you really have 2 separate DB2 databases (and, for some reason, don't want to migrate to a single database with multiple schemas): You can do this by defining a nickname in your first database.
This requires a somewhat convoluted process of defining a wrapper (CREATE WRAPPER), a server (CREATE SERVER), user mapping(s) (CREATE USER MAPPING) and finally the nickname (CREATE NICKNAME). It is generally easiest to do these tasks using the Control Center GUI because it will walk you through the process of defining each of these.

Grouping ETL Staging Tables With User Schemas?

I was thinking of putting staging tables and stored procedures that update those tables into their own schema. Such that when importing data from SomeTable to the datawarehouse, I would run a Initial.StageSomeTable procedure which would insert the data into the Initial.SomeTable table. This way all the procs and tables dealing with the Initial staging are grouped together. Then I'd have a Validation schema for that stage of the ETL, etc.
This seems cleaner than trying to uniquely name all these very similar tables, since each table will have multiple instances of itself throughout the staging process.
Question: Is using a user schema to group tables/procs/views together an appropriate use of user schemas in MS SQL Server? Or are user schemas supposed to be used for security, such as grouping permissions together for objects?
This is actually a recommended practice. Take a look at the Microsoft Business Intelligence ETL Design Practices from the Project Real. You will find (download doc from the first link) that they use quite a few schemata to group and identify objects in the warehouse.
In addition to dbo and etl, they also use admin, audit, part, olap and a few more.
I think it's appropriate enough, it doesn't really matter, you could use another database if you liked which is actually what we do.
I'm not sure why you would want a validation schema though, what are you going to do there?
Both the reasons you list (purpose/intent, security) are valid reasons to use schemas. Once you start using them, you should always specify schema when referencing an object (although I'm lazy and never specify dbo).
One trick we use is to have the same-named table in each of several schemas, combined with table partitioning (available in SQL 2005 and up). Load the data in first schema, then when it's validated "swap" the partition into dbo--after swapping the dbo partition into a "dumpster" schema copy of the table. Net Production downtime is measured in seconds, and it's all carefully wrapped in a declared transaction.

schema in sql server 2008

what is the difference between creating ordinary tables using 'dbo' and creating tables using schemas.How this schema works & supports the tables
A schema is just a container for DB objects - tables, views etc. It allows you to structure a very large database solution you might have. As a sample, have a look at the newer AdventureWorks sample databases - they have a number of schemata included, like "HumanResources" and so forth.
A schema can be a security boundary, e.g. you can give or deny certain users access to a schema as a whole. A schema can also be used to keep tables with the same name apart, e.g. you could create a "user schema" for each user of your application, and have a "Settings" table in each of them, holding that user's settings, e.g. "Bob.Settings", "Mary.Settings" etc.
In my experience, schemata are not used very often in SQL Server. It's a way to organize your database objects into containers, but unless you have a huge amount of database objects, it's probably something you won't really use much.
dbo is a schema.
See if this helps.
Schema seems to be a way of categorizing objects (tables/stored procs/views etc).
Think of it as a bucket to organize related objects based on functionality.
I am not sure, how logged in SQL user is tied to a specific schema though.

Resources