Sql server T SQL 2014 (Reusing same query) - sql-server

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

Related

Filter in Join instead of Where Clause

I'm adapting queries that hard code a filter of inclusion values in the join. When I Inner Join a table of values instead of hardcoding the values, I get more records back. Does anyone have any insight why?
The original query hardcodes the inclusion values in the inner join and it comes back with 1600 records
SELECT DISTINCT dat.HLV_ID, dat.CUR_VALUE_DATETIME, sde.CONCEPT_ID
FROM SMRTDTA_ELEM_DATA dat
INNER JOIN CLARITY_CONCEPT sde ON dat.ELEMENT_ID = sde.CONCEPT_ID
AND sde.CONCEPT_ID IN ('EPIC#....','EPIC#.....','EPIC#.....')
Inner Joining a list of inclusion values into a temp table brings back more results
IF OBJECT_ID('tempdb..#LOOKUPCODES') IS NOT NULL DROP TABLE #LOOKUPCODES;
SELECT sde.CONCEPT_ID code_id, 'clarity_eap.proc_id' as code_id_field
INTO #LOOKUPCODES
FROM CLARITY_CONCEPT sde
WHERE sde.CONCEPT_ID IN ('EPIC#....','EPIC#.....','EPIC#.....')
SELECT DISTINCT dat.HLV_ID, dat.CUR_VALUE_DATETIME , sde.CONCEPT_ID
FROM SMRTDTA_ELEM_DATA dat
INNER JOIN CLARITY_CONCEPT sde ON dat.ELEMENT_ID = sde.CONCEPT_ID
INNER JOIN #LOOKUPCODES l on l.code_id = sde.CONCEPT_ID

Inserting into new Table getting more records, CROSS JOIN, UPDATE

In my current data structure my OFFENSE table doesnt have all the columns that I need. For this reason I inner join it with several other table columns and insert it into a new table called TexasCCHPublicRecords created by me. This is my query:
INSERT INTO TexasCCHPublicRecords (OFF_IDN, TRS_IDN, AGY_TXT, DOO_DTE, AON_COD, AOL_TXT, LDA_CODE, GOC_COD, ADN_COD, ADD_TXT, ADA_DTE, REF_TXT,
IPN_NBR, ICA_NBR, DMV_COD, TRS_CODE, TRN_CODE, PERSON_ID, FIRST_NAME, LAST_NAME, DATE_OF_BIRTH, CDN, OffenseCode, OffenseName, CDNCode, ArrestingAgency,
ArrestingAgencyORI, ProsecutionAgency, ProsecutionAgencyORI)
SELECT o.* , trs.TRS_COD as 'TRS_CODE', trn.TRN_NBR as 'TRN_CODE', p.PER_IDN as 'PERSON_ID', nam.FNA_TXT as 'FIRST_NAME', nam.LNA_TXT as 'LAST_NAME',
birth.DOB_DTE as 'DATE_OF_BIRTH', cdnCode.CDN_VAL_TXT as 'CDN', offenseCode.OFF_COD as 'OffenseCode', offenseCode.LIT_TXT as 'OffenseName',
cdnCode.CDN_VAL_COD as 'CDNCode', arrestingAgency.ATR_TXT as 'ArrestingAgency', arrestingAgency.ORI_TXT as 'ArrestingAgencyORI',
prosecutionAgency.ATR_TXT as 'ProsecutionAgency',prosecutionAgency.ORI_TXT as 'ProsecutionAgencyORI'
FROM OFFENSE o
inner join CCH_PUBLIC.dbo.TRS trs on trs.TRS_IDN = o.TRS_IDN
inner join CCH_PUBLIC.dbo.TRN trn on trn.TRN_IDN = trs.TRN_IDN
inner join CCH_PUBLIC.dbo.PERSON p on p.IND_IDN = trn .IND_IDN
inner join CCH_PUBLIC.dbo.NAME nam on nam.PER_IDN = p.PER_IDN
inner join CCH_PUBLIC.dbo.BRTHDATE birth on birth.PER_IDN = p.PER_IDN
inner join CCH_PUBLIC.dbo.PROSECUTION prose on prose.TRS_IDN = o.TRS_IDN
inner join CCH_PUBLIC.dbo.AGENCY arrestingAgency on arrestingAgency.ORI_TXT = o.AGY_TXT
inner join CCH_PUBLIC.dbo.AGENCY prosecutionAgency on prosecutionAgency.ORI_TXT = o.REF_TXT
inner join CCH_PUBLIC.dbo.CRT_STAT crtStat on crtStat.TRS_IDN = o.TRS_IDN
inner join CCH_PUBLIC.dbo.CDN_COD cdnCode on cdnCode.CDN_VAL_COD = crtStat.CDN_COD
inner join CCH_PUBLIC.dbo.OFF_CODE offenseCode on offenseCode.OFF_COD = o.AON_COD
I would conclude that this table would select every offense in the OFFENSE table inner join it with the other tables and insert it into the TexasCCHPublicRecords
However after running this simple count
select count(*) as 'Offense Table Record Count' FROM OFFENSE
select count(*) as 'CCHPublicRecords Table Record Count' FROM TexasCCHPublicRecords
I end with these results:
Offense Table Record Count
11372377
CCHPublicRecords Table Record Count
49666836
There are 38 million more records in my new table. How did this happen? Is my query inserting repeated instances of the same offense row?
My goal is to SELECT an OFFENSE inner join it with the tables that are associated with it and INSERT that into my empty table. What am i doing wrong?
UPDATE
After reading one of the comments I realized that one of the tables was giving me 7 columns. Now I am trying to ONLY select the FIRST result. I am trying to do a CROSS APPLY however I am not sure what to place on the outside of the cross apply. This is my select Query:
SELECT o.*, trs.TRS_COD as 'TRS_CODE', trn.TRN_NBR as 'TRN_CODE', p.PER_IDN as 'PERSON_ID', nam.FNA_TXT as 'FIRST_NAME', nam.LNA_TXT as 'LAST_NAME',
birth.DOB_DTE as 'DATE_OF_BIRTH', cdnCode.CDN_VAL_TXT as 'CDN', offenseCode.OFF_COD as 'OffenseCode', offenseCode.LIT_TXT as 'OffenseName',
cdnCode.CDN_VAL_COD as 'CDNCode', arrestingAgency.ATR_TXT as 'ArrestingAgency', arrestingAgency.ORI_TXT as 'ArrestingAgencyORI',
prosecutionAgency.ATR_TXT as 'ProsecutionAgency',prosecutionAgency.ORI_TXT as 'ProsecutionAgencyORI'
FROM OFFENSE o
inner join CCH_PUBLIC.dbo.TRS trs on trs.TRS_IDN = o.TRS_IDN
inner join CCH_PUBLIC.dbo.TRN trn on trn.TRN_IDN = trs.TRN_IDN
inner join CCH_PUBLIC.dbo.PERSON p on p.IND_IDN = trn.IND_IDN
inner join CCH_PUBLIC.dbo.BRTHDATE birth on birth.PER_IDN = p.PER_IDN
inner join CCH_PUBLIC.dbo.PROSECUTION prose on prose.TRS_IDN = o.TRS_IDN
inner join CCH_PUBLIC.dbo.AGENCY arrestingAgency on arrestingAgency.ORI_TXT = o.AGY_TXT
inner join CCH_PUBLIC.dbo.AGENCY prosecutionAgency on prosecutionAgency.ORI_TXT = o.REF_TXT
inner join CCH_PUBLIC.dbo.CRT_STAT crtStat on crtStat.TRS_IDN = o.TRS_IDN
inner join CCH_PUBLIC.dbo.CDN_COD cdnCode on cdnCode.CDN_VAL_COD = crtStat.CDN_COD
inner join CCH_PUBLIC.dbo.OFF_CODE offenseCode on offenseCode.OFF_COD = o.AON_COD
CROSS APPLY (
SELECT TOP 1 *
FROM CCH_PUBLIC.dbo.NAME as nam
WHERE nam.PER_IDN = p.PER_IDN
) nam
is the nam out of the CROSS APPLY correct?

What type of SQL join is it in which the inner-join is not directly followed by an ON clause?

What is the name of this type of join? I've looked all over! The query is inner-joining back-to-back and then specifying two ON clauses.
Bonus points: What is the benefit of joining this way?
SELECT
<some columns>
FROM
ProductTypes AS t0
INNER JOIN Table1 AS t1
INNER JOIN Table2 AS t2
ON t2.CodeId = t1.CodeId
AND t2.[Enabled] = 1
ON t1.ClassId = t0.ClassId
Still it will be INNER JOIN.
It will interpreted as
SELECT <some columns>
FROM producttypes AS t0
INNER JOIN table2 AS t2
ON t1.classid = t0.classid
INNER JOIN table1 AS t1
ON t2.codeid = t1.codeid
AND t2.[enabled] = 1
Compiler is smart enough to rearrange the JOIN order
Here is demo of what's happening internally. I have used my own table's with similar JOIN order
Your query JOIN order
SELECT
*
FROM
users AS t0
INNER JOIN products AS t1
INNER JOIN orders AS t2
ON t2.productid = t1.productid
AND t2.productid = 1
ON t2.uid = t0.uid
Execution Plan
The rearranged JOIN order
SELECT
*
FROM
users AS t0
INNER JOIN orders AS t2
ON t2.uid = t0.uid
INNER JOIN products AS t1
ON t2.productid = t1.productid
AND t2.productid = 1
Execution Plan
As you can see both has identical execution plan. So there wont be any difference
This is a form of doing nested joins. There's no purpose with all inner unless you want to do it for readability. It can be useful if you use left outer. Consider:
SELECT
<some columns>
FROM
ProductTypes AS t0
LEFT OUTER JOIN Table1 AS t1
INNER JOIN Table2 AS t2
ON t2.CodeId = t1.CodeId
AND t2.[Enabled] = 1
ON t1.ClassId = t0.ClassId
Now this does something. If you did it without putting the t1/t0 at the end the t1/t2 inner would basically negate the fact that t1/t0 is a left outer. So doing it this way lets you have t0 records with no t1 records (just like a normal left outer join), but will only show the t1 records that ALSO have a t2. The inner join is enforced at this lower level.
See also:
http://sqlity.net/en/1435/a-join-a-day-nested-joins/
SQL join format - nested inner joins

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

T-SQL - Joining to database with derived name

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

Resources