TSQL: Create a view that accesses multiple databases - sql-server

I have a special case,
for example in table ta in database A, it stores all the products I buy
table ta(
id,
name,
price
)
in table tb in database B, it contain all the product that people can buy
table tb(
id,
name,
price
....
)
Can I create a view in database A to list all the products that I haven`t bought?

Yes you can - the t-sql syntax is the same as within any other cross database call (within a stored procedure for example).
To reference your tables in the second database you simply need:
[DatabaseName].[Schema].[TableName]
So you would end up with something like
CREATE VIEW [dbo].[YourView]
as
select
a.ID,
a.SomeInfo,
b.SomeOtherInfo
from TableInA a
join DatabaseB.dbo.TableInB b
on -- your join logic goes here
Note that this will only work on the same server - if your databases are on different servers them you will need to create a linked server.

As the other answers indicate, you can use the {LINKED_SERVER.}DATABASE.SCHEMA.OBJECT notation.
You should also be aware that cross-database ownership chaining is disabled by default.
So within a database, granting SELECT on a view allows a user who may not have SELECT on the underlying tables to still SELECT from the view. This may not work across to another database where the user does not have permissions on the underlying table.

Yes, views can reference three part named objects:
create view A.dbo.viewname as
select ... from A.dbo.ta as ta
join B.dbo.tb as tb on ta.id = tb.id
where ...
There will be problems down the road with cross db queries because of backup/restore consistency, referential integrity problems and possibly mirorring failover, but those problems are inherent in having the data split across dbs.

Related

How can I reference tables from multiple databases within the same server in a common table expression (CTE)?

I have a SQL Server 2014 Express with multiple databases. One of them has general tables with information common to the remaining databases (let's call this database UniversalData).
The other databases have information that is pertinent to a specific site (let's call one of these databases Site01Data). The universal data may change and I don't want to replicate it regularly to the other site-specific databases, so I want to include the UniversalData table in some queries, some of which involve CTEs.
What I am trying to accomplish:
WITH CTE1 AS
(
SELECT *
FROM UniversalData.dbo.someTable
),
CTE2 AS
(
SELECT *
FROM Site01Data.dbo.anotherTable
),
CTE3 AS
(
SELECT CTE1.field1, CTE2.field2
FROM CTE1
JOIN CTE2 ON CTE1.idx = CTE2.idx
)
SELECT *
FROM CTE3;
This doesn't generate an error, but I seem to get no data from the CTE1 in my final query (null result set). Intuitively, does this mean it is saving a temp table in the UniversalData database that is not accessible from the Site01Data database?
How can I use a CTE with tables from different databases on the same server?
There are lots of ways to do this..
You could read the tables in one database into a temp table on the second database and then join to it.. or join both of them on the fly.
but first.. refrain from doing select *.. specify the columns
You could go
select t1.column1,t2.column2
from UniversalData.dbo.someTable t1
inner join Site01Data.dbo.anotherTable t2
on t2.ida = t2.idx
and so onn.. it depends on which way you want to specify the join and what sort of join you want to choose..
This assumes that both the data bases are on the same instance.. else you will need linked servers
Specify servername.site1data.dbo.table etc and use linked servers if appropriate across different servernames

Find dependencies between tables in sql database

I have a Sql database with data. I have been asked to populate a fresh identical database with all the required master data so that the application is able to up and run for a new customer.
First approach
Delete all the data from database, run the application, sure i won't be even able to login. Observe errors, identify tables which need master data(sure User table at least), insert data. Then assume i am going to access a module. But without some master data it'll give me errors. Observe errors, identify tables which need master data, insert data.
But this seems not practical.
Second approach
While keeping the data in database, take one table at a time, using queries or sql server management studio tools, find all dependent tables. Keep the parent table data and delete child table data. Do this for all tables. In second round consider the remaining parent tables. Some table's data are inserted from application. Identify those and delete them. This way i can have relevant master data at the end. But i don't know how to approach this.
All these are my thoughts. Sure there might be many more approaches which are more precise and easier than these.I am confused with what to do. Please guide me. Thanks!
Here's a few queries you could use to figure out which table and column is referencing which table and column...
select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE
select * from INFORMATION_SCHEMA.columns
select * from INFORMATION_SCHEMA.tables
select * from sys.foreign_keys
select * from sys.foreign_key_columns
select * from [sys].[objects] where [name] = 'your_tablename'
For more, open Object Explorer (View Menu) and expand:
Databases/System Databases/Master/Views/System Views.
Also, check out any database diagrams there might be in Object Explorer:
Databases/Your_db_name/Database Diagrams.
How big is the database ?
No matter what you have to make proper documentation ?So better start with documentation.
You have to list all table one by one and identity if it is master table.
Remember the diff. between Delete or Truncate.
While doucmenting above query will come in handy.
Save the query and document for future need.
Most importantly,there should not be any error,even if any of the table is empty.
To find foreign key dependecies between tables you can use
SELECT FKT.name 'Parent table', CHT.name 'Child table' FROM sys.foreign_keys FK
JOIN sys.tables CHT ON FK.parent_object_id = CHT.object_id
JOIN sys.tables FKT ON FK.referenced_object_id = FKT.object_id
There is also ways to find dependencies in database views using system views.

how to select values from two tables

I have two tables arts and artsdetails.. artsId is the primary key in arts table foreign key in artdetails table. I am selecting values from both table but my query is giving error as
"Invalid object name 'artdetails'"
My query is:
SELECT arts.artsId, artdetails.mainImage
FROM artdetails
INNER JOIN arts ON artdetails.artsId = arts.artsId;
Please help.
You're probably not running the query in the database where these tables live.
If you're using SQL Server Management studio, look in the top left for a drop down containing the database names. It probably says 'master' (as that's the default). Select the one containing the tables you're using and re-run your query.
Failing that, check they're both running in the same schema as Tom suggests.
You can fully quality table names in your query like this:
SELECT a.artsId, ads.mainImage
FROM [DBNAME].[SCHEMA].artdetails ad
INNER JOIN [DBNAME].[SCHEMA].arts a ON ad.artsId = a.artsId;
Also using table abbreviations tidies things up a bit.

Any system table or view containing the information of all databases, schemas, tables and columns in SQL Server 2008?

I'm trying to find a system table or make some joins to get a table in which I can find all the columns of all the tables of all the schemas of all the databases of my server.
I'm doing this for academic purposes, so I can't use any stored procedure or function, I have to create it myself.
The point is to create a store procedure or function that receives a database name, a schema name and a table name as input parameters and throws a list of all the columns contained, but If I don't receive a table name, I should list all the columns of all the tables contained in the given database and schema. If I also don't receive a schema name as input parameter I should list all columns of all tables of all schemas in the given database.
Any ideas? As I say, I cannot use any stored procedure or function to do this.
This is what you need for all the columns of all the tables in the current database accessable by currect user:
http://msdn.microsoft.com/en-us/library/ms188348.aspx
To find the same from all databases, you have to connect to each of the databases and then access the system view.
If you connect as the dba user, you will have access to all tables in all schemas.
There are tables in the sys schema which may be of interest. sys.databases, sys.schemas, sys.tables, sys.columns all of which can be easily joined together and filtered to your needs.
sp_msforeachdb 'SELECT t.name FROM [?].sys.schemas s
INNER JOIN [?].sys.tables t ON s.[schema_id] = t.[schema_id]
INNER JOIN [?].sys.columns c ON c.[object_id] = t.[object_id]';

sql server: looking for table usage through out database

How would I figure out what type of sql code such as procs, functions, views etc. are interacting with my table called TABLE1 through out a given database. Sample code would be very helpful for me.
thanks
select so.name, so.xtype
from sysobjects so (nolock)
inner join syscomments sc (nolock) on sc.id = so.id
where sc.text like '%tablename%'
This code will search all SQL Server objects for a reference to your table. You have to run this query for each database.
If a stored procedure uses your table it will appear in this query. The same is true of functions, views, and triggers.
xtype tells you the type of object.
Here are the possible xtype values:
D = Field names
F = Foreign Key
FN = Function
P = Stored Procedures
PK = Primary Key
S = System Tables
U = User tables
V = Hidden tables
Not enough info in your question, but one thing you can do is use SQL Profiler to profile where INSERTs, UPDATEs, and DELETEs are coming from.
I assume you are talking about how an app is interacting with data and what name (of say a sproc) is doing the insert / update / delete.
Look at SQL Profiler, it comes with your client tools install. Filter it to only show connections to your database (either db name or ID).
If you've been good and created your SPs/views/functions after your table was created, sp_depends will tell you evertyhing referencing the table. Exept for dynamic sql that is.

Resources