T-SQL - Joining to database with derived name - sql-server

I need to be able to join to a different database (on the same server), and the name of the database I need to join to is dependent on the record being examined. I've got something along the lines of
SELECT *
FROM orders o
INNER JOIN orderdetail od ON od.okey = o.okey
INNER JOIN scheduledetail scheddet on scheddet.odkey = od.odkey
INNER JOIN schedules sched on sched.schedid = scheddet.schedid
INNER JOIN databases db on db.dbdate = sched.releasedate
INNER JOIN [db.dbname].detail det on det.odkey = od.odkey
However, as far as I can tell transact SQL won't allow this kind of join syntax. Any ideas?

If all the detail tables have the same columns, you could create a view that wraps all of them.
DECLARE #sql varchar(max);
SELECT
#sql = COALESCE(#sql + ' UNION ALL ','CREATE VIEW unified_details AS ')
+ 'SELECT *,'+QUOTENAME([dbname])+' AS [dbname] FROM '+QUOTENAME([dbname])+'.[dbo].[detail]'
FROM databases;
EXEC sp_executesql #sql;
SELECT *
FROM orders o
INNER JOIN orderdetail od ON od.okey = o.okey
INNER JOIN scheduledetail scheddet on scheddet.odkey = od.odkey
INNER JOIN schedules sched on sched.schedid = scheddet.schedid
INNER JOIN databases db on db.dbdate = sched.releasedate
INNER JOIN unified_details det on det.odkey = od.odkey and db.dbname = det.dbname

Related

How to insert keys from one database to another?

Here is my code for inserting values from AdventureWorks to custom database.
I needed to transfer identifiers from AdventureWorks too but copy of identifiers are not allowed. So I thought using distinct with identifier would be enough, but I still get error about inserting duplicates.
If you could comment and tell me what I am doing wrong I would be very grateful.
Thank you!
Here is my full attempt: https://pastebin.com/ZPniteh1
set identity_insert proizvodi ON
insert into proizvodi (ProizvodID, Sifra, Naziv, Kategorija, Podkategorija, Boja, Cijena, StanjeZaliha)
select distinct
p.ProductID, p.ProductNumber,p.[Name], pc.[Name],psc.[Name],
p.Color, p.ListPrice, pii.Quantity
from
AdventureWorks2017.Production.Product as p
join
AdventureWorks2017.Production.ProductSubcategory as psc on psc.ProductSubcategoryID = p.ProductSubcategoryID
join
AdventureWorks2017.Production.ProductCategory as pc on pc.ProductCategoryID = psc.ProductCategoryID
inner join
AdventureWorks2017.Production.ProductInventory as pii on pii.ProductID = p.ProductID
inner join
AdventureWorks2017.Sales.SalesOrderDetail as sod on sod.ProductID = p.ProductID
inner join
AdventureWorks2017.Sales.SalesOrderHeader as soh on soh.SalesOrderID = sod.SalesOrderID
inner join
AdventureWorks2017.Sales.SalesTerritory as st on st.TerritoryID = soh.TerritoryID
inner join
AdventureWorks2017.Production.[Location] as l on l.LocationID = pii.LocationID
where
st.[Group] ='Europe'
order by
p.ProductID
set identity_insert proizvodi OFF

Return Stored Procedures, tables and columns in reference to a particular database

I am looking to write a query that will return all of the stored procedures and views that reference a specific database that I am looking to rebuild. I also need the query to return the columns and table names that the returned stored procedures / views contain in reference to the database being rebuilt.
I have a query right now that will return the stored procs and views, but have been unsuccessful in returning the column and table names that reference the database.
SELECT Distinct so.Name, so.type--, sc.text
FROM sysobjects so(NOLOCK)
INNER JOIN syscomments sc (NOLOCK) on so.Id = sc.ID
WHERE so.Type in( 'p' , 'v')
AND sc.Text LIKE '%membership_dw.%'
ORDER BY so.Name
Membership_DW is the name of the database where the stored procedures and views are currently stored, and it is also the database that is being recreated.
Here is a quick and dirty query to do it
;WITH cte as(
select *
from sys.sysdepends t1
inner join sys.objects t2 on t1.depid = t2.object_id
where t2.type = 'U' and is_ms_shipped = 0)
SELECT t5.name as SP_NAME, t6.name as TBL_NAME, t9.name COLNAME from sys.objects t5
INNER JOIN cte t6 on t6.id = t5.object_id
INNER JOIN sys.columns t9 on t6.object_id = t9.object_id
where t5.is_ms_shipped = 0 and t6.name not like 'sys%'
order by sp_name, TBL_NAME

Sql server T SQL 2014 (Reusing same query)

I have a query which joins 3,4 tables(like select * from table1 join table2 join table3) and the same query is used in my stored procedure multiple time. Is there any way to keep that query in one place and i can use it in my entire stored procedure(with in a single stored procedure)?
SELECT p.PK_PatientID
FROM Patients p
INNER JOIN PT ON e.FK_PatientID = p.PK_PatientID
INNER JOIN PN n ON n.FK_PatientEncounterID = e.PK_PatientEncounterID
INNER JOIN BP ep ON ep.FK_PatientEncounterID = e.PK_PatientEncounterID
INNER JOIN SOP pd ON ep.FK_SharedProcedureDetailID = pd.PK_SharedOfficeProcedureDetailID
INNER JOIN CQM vs ON pd.FK_SharedProcedureCode = vs.Code
This is the query i want to use it in my procedure multiple time
You could use Temp table or Table variable and insert data into it,if you are using the query multiple times
If you don't want to use temp tables or tables variables for reasons unknown,you could use a view
You can store your select query in a view:
CREATE VIEW vW_Example
AS
SELECT p.PK_PatientID
FROM Patients p
INNER JOIN PT ON e.FK_PatientID = p.PK_PatientID
INNER JOIN PN n ON n.FK_PatientEncounterID = e.PK_PatientEncounterID
INNER JOIN BP ep ON ep.FK_PatientEncounterID = e.PK_PatientEncounterID
INNER JOIN SOP pd ON ep.FK_SharedProcedureDetailID = pd.PK_SharedOfficeProcedureDetailID
INNER JOIN CQM vs ON pd.FK_SharedProcedureCode = vs.Code
Then you can call the view like this:
SELECT * FROM vW_Example

Updating MS SQL objects with dependencies

I have sql scripts DROP ... CREATE... for views, procedures, triggers, functions (in files on disk). I need to run this scripts to update database structure.
But order of executing scripts is important. Because if view1 depends on view2, and I run scripts for view1 first, an error may occurs.
Let's suppose that there are no adscititious dependencies in my scripts, so database knows about all dependencies.
Is there a way to select all this objects names from sql server in dependency order? So I can run scripts in this order and not afraid about above errors.
I wrote this sql:
SET NOCOUNT ON
declare #deps TABLE (name nvarchar(512), dep_name nvarchar(512))
declare #ordered TABLE (name nvarchar(512), [level] INT)
insert #deps(name, dep_name)
SELECT DISTINCT CAST(OBJ.name as nvarchar(512)) AS ObjectName,
CAST(REFOBJ.name as nvarchar(512)) AS ReferencedObjectName
FROM sys.sql_dependencies AS DEP
INNER JOIN
sys.objects AS OBJ
ON DEP.object_id = OBJ.object_id
INNER JOIN
sys.schemas AS SCH
ON OBJ.schema_id = SCH.schema_id
INNER JOIN sys.objects AS REFOBJ
ON DEP.referenced_major_id = REFOBJ.object_id
INNER JOIN sys.schemas AS REFSCH
ON REFOBJ.schema_id = REFSCH.schema_id
LEFT JOIN sys.columns AS REFCOL
ON DEP.class IN (0, 1)
AND DEP.referenced_minor_id = REFCOL.column_id
AND DEP.referenced_major_id = REFCOL.object_id
WHERE OBJ.type_desc IN ('VIEW','SQL_STORED_PROCEDURE','SQL_INLINE_TABLE_VALUED_FUNCTION','SQL_TRIGGER','SQL_SCALAR_FUNCTION')
AND REFOBJ.type_desc IN ('VIEW','SQL_STORED_PROCEDURE','SQL_INLINE_TABLE_VALUED_FUNCTION','SQL_TRIGGER','SQL_SCALAR_FUNCTION')
insert #ordered(name, [level])
select distinct d1.dep_name, 1 as [level]
from #deps d1
LEFT JOIN #deps d2 ON d1.dep_name = d2.name
where d2.name IS NULL
WHILE EXISTS(select * from #deps)
BEGIN
delete d
FROM #deps d
JOIN #ordered o ON d.name = o.name
insert #ordered(name, [level])
SELECT DISTINCT d0.name, (select MAX([level]) + 1 FROM #ordered)
FROM #deps d0
LEFT JOIN (
SELECT d.name
from #deps d
LEFT JOIN #ordered o ON d.dep_name = o.name
WHERE o.name IS NULL
) dfilter ON d0.name = dfilter.name
WHERE dfilter.name is NULL
END
select * from #ordered
ORDER by level asc

How to get values from 3 tables?

CREATE PROCEDURE spJoin3Tables
AS
BEGIN
SELECT
tbl_Jobs.JobTitle, tbl_Company.CompName
FROM
tbl_Jobs
INNER JOIN
tbl_Company ON tbl_Jobs.CompID = tbl_Company.ID
SELECT
tbl_Cities.CityName
FROM
tbl_Cities
INNER JOIN
tbl_JobCities ON tbl_Cities.ID = tbl_JobCities.CityID
INNER JOIN
tbl_Jobs ON tbl_JobCities.JobID = tbl_Jobs.ID
END
The result is two tables. I want to get all three columns in one table - what will be the query?
You just need to add the company table and the columns from the first query to the second query and make sure to join on the company id.
SELECT
tbl_Cities.CityName, tbl_Jobs.JobTitle, tbl_Company.CompName
FROM
tbl_Cities
INNER JOIN
tbl_JobCities ON tbl_Cities.ID = tbl_JobCities.CityID
INNER JOIN
tbl_Jobs ON tbl_JobCities.JobID = tbl_Jobs.ID
INNER JOIN
tbl_Company ON tbl_Jobs.CompID = tbl_Company.ID
USING INNER JOIN U CAN GET ALL DATE. IF IN CASE ANY TABLE IN ID COLUMNS NULL VALUE THEN USER LEFT JOIN
SELECT tbl_Jobs.JobTitle, tbl_Company.CompName , tbl_Cities.CityName
FROM tbl_Jobs
INNER JOIN tbl_Company ON tbl_Jobs.CompID = tbl_Company.ID
INNER JOIN tbl_JobCities ON tbl_JobCities.JobID = tbl_Jobs.ID
INNER JOIN tbl_Cities ON tbl_Cities.ID = tbl_JobCities.CityID

Resources