SQL Query join issues - sql

I am using SQL Server 2005.
I'm having some issues when executing this query.
My code is
ALTER PROCEDURE [dbo].[Get]
#ApplicantID int
AS
BEGIN
SELECT
isnull(M_EvalApplicationStatuses.EvalApplicationStatus,'') EvalApplicationStatus,
isnull(M_Users.CompletionMailSent,'') MailSent,
isnull(APP_Applications.FirstName,'') FirstName,
isnull(APP_Applications.LastName,'') LastName,
isnull(M_Users.UserName,'') UserName,
isnull(APP_Applications.DocTrackingGenComment,'') DocTrackingGenComment
FROM
APP_Applications
left outer join
M_Users
ON
APP_Applications.UserID = M_Users.UserID
left outer join
M_EvalApplicationStatuses
ON
APP_Applications.Status = M_EvalApplicationStatuses.EvalApplicationStatusID and M_EvalApplicationStatuses.Status = 1
WHERE
ApplicantID =#ApplicantID
END
This now works perfectly. But I want to get data from another table, so I just left join that table to this query. Here I have found the issue. My new table name is [APP_DocumentTracking] and the below query I used to retrieve data.
SELECT DISTINCT
isnull(APP_DocumentTracking.Date,'') Date,
isnull(APP_DocumentTracking.IntervTime,'') IntervTime,
isnull(APP_DocumentTracking.Telephoneinterview,'') Telephoneinterview
FROM [APP_DocumentTracking]
where APP_DocumentTracking.ApplicantID = #ApplicantID
These two queries are separately working fine... but I want to join these two queries and the result will be get in one table. How can I do this? plz help me

As per your comment in sarathkumar's answer the problem is Ambiguous column name 'ApplicantID'. Try the below for that problem. I have updated the where clause from your comment.
left outer join [APP_DocumentTracking] on [APP_DocumentTracking].ApplicantID=APP_Applications.ApplicantID
WHERE [APP_DocumentTracking].ApplicantID =#ApplicantID END

ALTER PROCEDURE [dbo].[Get]
#ApplicantID int
AS
BEGIN
SELECT
isnull(M_EvalApplicationStatuses.EvalApplicationStatus,'') EvalApplicationStatus,
isnull(M_Users.CompletionMailSent,'') MailSent,
isnull(APP_Applications.FirstName,'') FirstName,
isnull(APP_Applications.LastName,'') LastName,
isnull(M_Users.UserName,'') UserName,
isnull(APP_Applications.DocTrackingGenComment,'') DocTrackingGenComment
FROM APP_Applications
left outer join M_Users
ON APP_Applications.UserID = M_Users.UserID
left outer join
M_EvalApplicationStatuses
ON
APP_Applications.Status = M_EvalApplicationStatuses.EvalApplicationStatusID and M_EvalApplicationStatuses.Status = 1
left join
(
SELECT DISTINCT
isnull(APP_DocumentTracking.Date,'') Date,
isnull(APP_DocumentTracking.IntervTime,'') IntervTime,
isnull(APP_DocumentTracking.Telephoneinterview,'') Telephoneinterview
APP_DocumentTracking.ApplicantID
FROM [APP_DocumentTracking]
where APP_DocumentTracking.ApplicantID = #ApplicantID
) AliasSubquery
on 1=1
WHERE
ApplicantID =#ApplicantID
END

Just join as a subquery with first and second one .Please update the structure in SqlFiddle or here Itself.Then it will be easy to give u the answer...
Here is the code
ALTER PROCEDURE [dbo].[Get]
#ApplicantID int
AS
BEGIN
SELECT
isnull(M_EvalApplicationStatuses.EvalApplicationStatus,'') EvalApplicationStatus,
isnull(M_Users.CompletionMailSent,'') MailSent,
isnull(APP_Applications.FirstName,'') FirstName,
isnull(APP_Applications.LastName,'') LastName,
isnull(M_Users.UserName,'') UserName,
isnull(APP_Applications.DocTrackingGenComment,'') DocTrackingGenComment
,Trace.*
FROM
APP_Applications
left outer join
M_Users
ON
APP_Applications.UserID = M_Users.UserID
left outer join
M_EvalApplicationStatuses
ON
APP_Applications.Status = M_EvalApplicationStatuses.EvalApplicationStatusID and M_EvalApplicationStatuses.Status = 1
LEFT JOIN
(SELECT DISTINCT
isnull(APP_DocumentTracking.Date,'') Date,
isnull(APP_DocumentTracking.IntervTime,'') IntervTime,
isnull(APP_DocumentTracking.Telephoneinterview,'') Telephoneinterview
FROM [APP_DocumentTracking]
where APP_DocumentTracking.ApplicantID = #ApplicantID
) AS Trace
ON APP_Applications.ApplicantID = Trace.ApplicantID
WHERE APP_Applications.ApplicantID =#ApplicantID
END
Cheers.

Related

Find all SELECT statements without a WHERE clause using a regex

I'm trying to scan my codebase to find all select queries without a where clause using regex. The results will be fed into an IDE or a grep file output, but must contain the full matching queries only.
My biggest challenge is getting the entire statement without the WHERE. The caveats are:
some selects don't have a where but also don't have a FROM
some selects target a database view (always starts with a vw) which don't need a where clause
Here's a sample list of all queries fetched from one file:
'
DECLARE #RowsAffected INT = 0;
INSERT INTO tblInvoice (InvID, OcID, InvTimeStamp)
SELECT DISTINCT OcInvID, OcID, GETDATE() AS InvTimeStamp
FROM tblOrderCost OC WITH(NOLOCK)
INNER JOIN tblVendor WITH(NOLOCK) ON InvVendorID = VendorID AND VendorType = 1 -- 1 for supplier.
INNER JOIN #tmpOpID tmp WITH(NOLOCK) ON tmp.OpID = OcOpID
WHERE id = ' . quote($order_id, NUMERIC);
$sql = ' SELECT rphrpid,rphwho,rphdate,rphnotes,opid
FROM tblReplacementPartHistory (nolock)
INNER JOIN tblReplacementPart (nolock)
ON rphrpid = rpid
INNER JOIN tblOrderProduct (nolock)
ON rpopid = opid
WHERE oporid =' . quote($order_id, NUMERIC)
. 'ORDER BY rphrpid';
select * from table where id = 1;
'
select count()
';
DECLARE #RowsAffected INT = 0;
INSERT INTO tblInvoice (InvID, OcID, InvTimeStamp)
SELECT DISTINCT OcInvID, OcID, GETDATE() AS InvTimeStamp
FROM tblOrderCost OC WITH(NOLOCK)
INNER JOIN tblVendor WITH(NOLOCK) ON InvVendorID = VendorID AND VendorType = 1
INNER JOIN #tmpOpID tmp WITH(NOLOCK) ON tmp.OpID = OcOpID';
$sql = ' SELECT rphrpid,rphwho,rphdate,rphnotes,opid
FROM tblReplacementPartHistory (nolock)
INNER JOIN tblReplacementPart (nolock)
ON rphrpid = rpid
INNER JOIN tblOrderProduct (nolock)
ON rpopid = opid
ORDER BY rphrpid';
SELECT rphrpid,rphwho,rphdate,rphnotes,opid
FROM vwOrder';
select * from tbl;
I tried several variations of regex patterns and the closest I got was finding matches with the WHERE line stripped out. I would like to have the entire match made only if the query does not have a WHERE clause. I tried the following
SELECT(.*)(\s)*FROM(\s|.)+?((?!.*where))(?=(';|";|;))
SELECT\s*(?!.*\s*where|vw(\w)*).*\s*(';|";|;)
SELECT[^;\n]*(?:\n(?![^\n;]*where)[^;\n]*)*\n[\n]*
The work can also be tested in the regex101 sandbox: https://regex101.com/r/jvbLOE/1
What I expect to see, given the sample data, is only three matches
1. SELECT DISTINCT OcInvID, OcID, GETDATE() AS InvTimeStamp
FROM tblOrderCost OC WITH(NOLOCK)
INNER JOIN tblVendor WITH(NOLOCK) ON InvVendorID = VendorID AND VendorType = 1
INNER JOIN #tmpOpID tmp WITH(NOLOCK) ON tmp.OpID = OcOpID';
2. SELECT rphrpid,rphwho,rphdate,rphnotes,opid
FROM tblReplacementPartHistory (nolock)
INNER JOIN tblReplacementPart (nolock)
ON rphrpid = rpid
INNER JOIN tblOrderProduct (nolock)
ON rpopid = opid
ORDER BY rphrpid';
3. select * from tbl;
You can use following regex to match select queries not having a where clause in it based on your example.
/(?!.*where)select.*?;/gis
Regex 101 example:
https://regex101.com/r/XaGXp6/1

string_agg is to slow with big data and i need a faster solution

I am working with contacting a string from a result and it is taking to long to execute
this is the solution I have:
declare #damagedParties table (caseid varchar(max),FirstName varchar(max),LastName varchar(max),damagedName varchar(max))
insert #damagedParties
select t.caseid,ped.FirstName as FirstName,ped.LastName,concat(ped.FirstName,' ',ped.LastName) as damagedName
from [Case] t
inner join [KCC].[dbo].[Party] p1 on p1.CaseId = t.caseid
LEFT JOIN Person ped ON ped.PersonOrBusinessId = ped.PersonOrBusinessId and p1.PartyTypeRefData = 'kpcparty$PARTY_INJUREDPARTY_F'
select string_agg(d.damagedName,', ')
from #damagedParties d
group by d.caseid
The LEFT JOIN condition in the first query joins the Person table to itself on PersonOrBusinessId. Presumably, the JOIN should be from Person table to the Party table? Something like this
insert #damagedParties
select t.caseid, ped.FirstName, ped.LastName,
concat(ped.FirstName,' ',ped.LastName) as damagedName
from [Case] t
join [KCC].[dbo].[Party] p1 on p1.CaseId = t.caseid
left join Person ped ON p1.PersonOrBusinessId = ped.PersonOrBusinessId
where p1.PartyTypeRefData = 'kpcparty$PARTY_INJUREDPARTY_F';

Passing different column values to where clause

SELECT pims.icicimedicalexaminerreport.id,
pims.icicimerfemaleapplicant.adversemenstrualid,
pims.icicimerfemaleapplicant.pregnantid,
pims.icicimerfemaleapplicant.miscarriageabortionid,
pims.icicimerfemaleapplicant.breastdiseaseid,
pims.pimscase.tiannumber
FROM pims.pimscase
INNER JOIN pims.digitization
ON pims.pimscase.digitizationid = pims.digitization.id
INNER JOIN pims.medicalexaminerreport
ON pims.digitization.medicalexaminerreportid =
pims.medicalexaminerreport.id
INNER JOIN pims.icicimedicalexaminerreport
ON pims.medicalexaminerreport.id =
pims.icicimedicalexaminerreport.id
INNER JOIN pims.icicimerfemaleapplicant
ON pims.icicimedicalexaminerreport.id =
pims.icicimerfemaleapplicant.id
WHERE pims.pimscase.tiannumber = 'ICICI1234567890'
which gives me the following output
Now I want to use the above output values to select the rows from the table "YesNoAnswerWithObservation"
I imagine it should look something like this Select * from YesNoAnswerWithObservation Where Id in (22,27,26,...23)
Only instead of typing the values inside IN clause I want to use the values in each column resulting from above-mentioned query.
I tried the below code but it returns all the rows in the table rather than rows mentioned inside the In
SELECT pims.yesnoanswerwithobservation.observation,
graphitegtccore.yesnoquestion.description,
pims.yesnoanswerwithobservation.id ObservationId
FROM pims.yesnoanswerwithobservation
INNER JOIN graphitegtccore.yesnoquestion
ON pims.yesnoanswerwithobservation.yesnoanswerid =
graphitegtccore.yesnoquestion.id
WHERE EXISTS (SELECT pims.icicimedicalexaminerreport.id,
pims.icicimerfemaleapplicant.adversemenstrualid,
pims.icicimerfemaleapplicant.pregnantid,
pims.icicimerfemaleapplicant.pelvicorgandiseaseid,
pims.icicimerfemaleapplicant.miscarriageabortionid,
pims.icicimerfemaleapplicant.gynocologicalscanid,
pims.icicimerfemaleapplicant.breastdiseaseid,
pims.pimscase.tiannumber
FROM pims.pimscase
INNER JOIN pims.digitization
ON pims.pimscase.digitizationid =
pims.digitization.id
INNER JOIN pims.medicalexaminerreport
ON pims.digitization.medicalexaminerreportid =
pims.medicalexaminerreport.id
INNER JOIN pims.icicimedicalexaminerreport
ON pims.medicalexaminerreport.id =
pims.icicimedicalexaminerreport.id
INNER JOIN pims.icicimerfemaleapplicant
ON pims.icicimedicalexaminerreport.id =
pims.icicimerfemaleapplicant.id
WHERE pims.pimscase.tiannumber = 'ICICI1234567890')
Any help or a nudge in the right direction would be greatly appreciated
Presumably you want the ids from the first query:
SELECT awo.observation, ynq.description, ynq.id as ObservationId
FROM pims.yesnoanswerwithobservation awo JOIN
graphitegtccore.yesnoquestion ynq
ON awo.yesnoanswerid = ynq.id
WHERE ynq.id = (SELECT mer.id
FROM pims.pimscase c JOIN
pims.digitization d
ON c.digitizationid = d.id JOIN
pims.medicalexaminerreport mer
ON d.medicalexaminerreportid = mer.id JOIN
pims.icicimedicalexaminerreport imer
ON mer.id = imer.id JOIN
pims.icicimerfemaleapplicant ifa
ON imer.id = ifa.id
WHERE c.tiannumber = 'ICICI1234567890'
) ;
Notice that table aliases make the query much easier to write and to read.

how to perform Two select query in one stored procedure in sql server

I am trying to perform two select query in one stored procedure. But its not giving me any output. There is no error but records are not being displayed.
First I tried this stored Procedure
CREATE PROCEDURE [dbo].[Sp_PriceList_Die_Wise]
#DieNo As Nvarchar(15),
#MetalCode As Int
AS
BEGIN
Select CP.BatchQty,CP.CastingPrice,U.UNITName As 'Unit',MachPrice,U.UNITName As 'M/C Unit' from CustomerPriceList As CP Left Outer Join UNITMaster As U On CP.MUNITID=U.UNITID where MOULDCODE=#DieNo And METALCODE=#MetalCode
SELECT TOP (10) SubOADetail.OANO, SubOADetail.ID, SubOADetail.QTY, SubOADetail.RATE, UNITMaster.UNITName As Unit, OATest.MachPrices, UNITMaster_1.UNITName AS Unit FROM UNITMaster AS UNITMaster_1 RIGHT OUTER JOIN OATest ON UNITMaster_1.UNITID = OATest.MachUnitID RIGHT OUTER JOIN SubOADetail LEFT OUTER JOIN UNITMaster ON SubOADetail.UNIT = UNITMaster.UNITID ON OATest.ID = SubOADetail.ID AND OATest.OANO = SubOADetail.OANO LEFT OUTER JOIN OADetails ON SubOADetail.OANO = OADetails.OANO WHERE SubOADetail.MOULDCODE = #DieNo AND SubOADetail.METALCODE =#MetalCode ORDER BY OADetails.OADATE DESC
END
This gives me output like this
but I want the output in single table so I created this stored procedure
CREATE PROCEDURE [dbo].[Sp_PriceList_Die_Wise]
#DieNo As Nvarchar(15),
#MetalCode As Int
AS
BEGIN
WITH main AS
(
Select CP.BatchQty,CP.CastingPrice,U.UNITName As 'Unit',
MachPrice,U.UNITName As 'M/C Unit' from CustomerPriceList As CP
Left Outer Join UNITMaster As U On CP.MUNITID=U.UNITID
where MOULDCODE=#DieNo And METALCODE=#MetalCode
), sub AS
(
SELECT TOP (10) SubOADetail.OANO, SubOADetail.ID, SubOADetail.QTY, SubOADetail.RATE,
UNITMaster.UNITName As Unit, OATest.MachPrices, UNITMaster_1.UNITName AS MCUnit
FROM UNITMaster AS UNITMaster_1 RIGHT OUTER JOIN OATest ON UNITMaster_1.UNITID = OATest.MachUnitID
RIGHT OUTER JOIN SubOADetail LEFT OUTER JOIN UNITMaster ON SubOADetail.UNIT = UNITMaster.UNITID
ON OATest.ID = SubOADetail.ID AND OATest.OANO = SubOADetail.OANO LEFT OUTER JOIN OADetails
ON SubOADetail.OANO = OADetails.OANO WHERE SubOADetail.MOULDCODE = #DieNo
AND SubOADetail.METALCODE =#MetalCode ORDER BY OADetails.OADATE DESC
)
SELECT *
FROM main m join sub s
ON m.MachPrice = s.MachPrices
END
But this gives me blank record like this
You are using INNER JOIN, and your first table (main) don't have any records, so you will not get any output.
If you want to select from other table even if matching records are not there in the main, you need to change your JOIN to RIGHT JOIN like following.
SELECT *
FROM main m right join sub s
ON m.MachPrice = s.MachPrices
EDIT:
RIGHT JOIN will work for the provided sample data, in case if you have data where left CTE don't have matching records in right CTE or vise versa and you still want to select the records, for such scenario you need a combination of LEFT JOIN and RIGHT JOIN, for this you can use FULL OUTER JOIN like following.
SELECT *
FROM main m full outer join sub s
ON m.MachPrice = s.MachPrices

SQL Selecting rows with not the same condition for all

I have to create SQL query that select persons datas. Every person has several grades and I have to select first by time for everyone. I don't know how do it because conditional is different for every person. Below is my current code which doesn't works.
SELECT s.sol_last_name,
g.grade_name,
MIN(sg.sol_grade_date_from)
FROM [dbo].[dim_s####] AS s
LEFT JOIN [dbo].[fact_s####_grade] AS sg ON s.sol_key = sg.sol_grade_sollers_key
LEFT JOIN [dbo].[dim_grade] AS g ON g.grade_key = sg.sol_grade_grade_key
GROUP BY s.sol_last_name,
g.grade_name
HAVING MIN(sg.sol_grade_date_from) = sg.sol_grade_date_from
You can put the earliest date in a subquery, and then inner join there:
SELECT s.sol_last_name,
g.grade_name,
sg.sol_grade_date_from
FROM [dbo].[dim_s####] AS s
INNER JOIN (
select sol_grade_grade_key
,min(sol_grade_date_from) as sol_grade_date_
from from [dbo].[dim_grade]
GROUP BY sol_grade_grade_key) AS g
ON g.grade_key = sg.sol_grade_grade_key
LEFT JOIN [dbo].[fact_s####_grade] AS sg
ON s.sol_key = sg.sol_grade_sollers_key
Use a Common Table Expression (cte) to save some typing. Then do a NOT EXISTS to return a row only if same sol_last_name has no older grade.
WITH CTE (sol_last_name, grade_name, grade_date_from) AS
(
SELECT s.sol_last_name,
g.grade_name,
sg.sol_grade_date_from
FROM [dbo].[dim_s####] AS s
LEFT JOIN [dbo].[fact_s####_grade] AS sg ON s.sol_key = sg.sol_grade_sollers_key
LEFT JOIN [dbo].[dim_grade] AS g ON g.grade_key = sg.sol_grade_grade_key
)
select sol_last_name, grade_name, grade_date_from
from cte as t1
where not exists (select 1 from cte t2
where t2.sol_last_name = t1.sol_last_name
and t2.grade_date_from < t2.grade_date_from)