Inner Join in stored procedure - sql

I have this stored procedure:
ALTER PROCEDURE [dbo].[Get_All_Items]
AS
BEGIN
SELECT
ItemID, ItemName, CategoryID, CountryID,
ItemSize, ColorID, ProductionDate, ExpiryDate,
UnitName, FirstUnitBarcode, FirstItemQuantity,
FirstUnitDefult, FirstUnitLimit,
UnitsTbl.SecondUnit, SecondUnitBarcode, SecondItemQuantity,
SecondUnitDefult, SecondUnitLimit,
ThirdUnit, ThirdUnitBarcode, ThirdItemQuantity,
ThirdUnitDefult, ThirdUnitLimit, UnitDefult,
ItemImage, ItemStatus, ItemsMainTbl.Nots,
ItemsMainTbl.CreatedBy, ItemsMainTbl.CreatedDate,
ItemsMainTbl.ModifiedBy, ItemsMainTbl.ModifiedDate
FROM
ItemsMainTbl
INNER JOIN
UnitsTbl ON ItemsMainTbl.FirstUnit = UnitsTbl.UnitID
INNER JOIN
UnitsTbl ON ItemsMainTbl.SecondUnit = UnitsTbl.UnitID
END
Conditions:
ItemsMainTbl.FirstUnit = UnitsTbl.UnitID
ItemsMainTbl.SecondUnit = UnitsTbl.UnitID
ItemsMainTbl.ThirdUnit = UnitsTbl.UnitID
How to join all three tables on that common column?
I got only the first one
ItemsMainTbl.FirstUnit = UnitsTbl.UnitID
Thanks

If you want to join the same table multiple times, you need to specify an alias for each instance of the joined table, like this:
SELECT *
FROM ItemsMainTbl
INNER JOIN UnitsTbl u1 ON ItemsMainTbl.FirstUnit = u1.UnitID
INNER JOIN UnitsTbl u2 ON ItemsMainTbl.SecondUnit = u2.UnitID
INNER JOIN UnitsTbl u3 ON ItemsMainTbl.ThirdUnit = u3.UnitID
Then in the select statement, you can differentiate between the joined instances, like this:
SELECT u1.Barcode, -- Barcode from FirstUnit
u2.Barcode, -- Barcode from SecondUnit
u3.Barcode -- Barcode from ThirdUnit

You need to define reference for you UnitsTbl. Think of these references as new objects of same class, in terms of OOP. Also, it is a good habit to use references for whenever querying over a table.
SELECT *
FROM
ItemsMainTbl t1
INNER JOIN
UnitsTbl u1 ON t1.FirstUnit = u1.UnitID
INNER JOIN
UnitsTbl u2 ON t1.SecondUnit = u2.UnitID
INNER JOIN
UnitsTbl u3 ON t1.ThirdUnit = u3.UnitID

Related

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.

Multiple Join not working on two string attributes

I have the following issue:
I have several tables in my Database, in order to check for a specific criteria I have to join several tables, where I use the following statement:
SELECT *
FROM (SELECT * FROM (((((((((SELECT * FROM table1 WHERE tab1_id = 1) AS A
INNER JOIN (SELECT * FROM table2 WHERE tab2_variable IS NOT NULL) AS B
ON A.variable = B.variable)
INNER JOIN (SELECT table3.*, IIF(year='XXXX', 0, 1) AS flag FROM table3) AS C
ON A.h_name = C.h_name)
INNER JOIN (SELECT * FROM table4 WHERE s_flag = 0) AS D
ON C.v_type = D.v_type)
INNER JOIN table5
ON C.ng_type = table5.ng_type)
INNER JOIN table6
ON C.part = table6.part)
INNER JOIN table7
ON C.ifg = table7.ifg)
INNER JOIN table8
ON C.v_type = table8.v_type AND C.ng_typ = table8.ng_typ AND C.ntr_flag = table8.ntr_flag)
INNER JOIN table9
ON table8.ifg_sii_id = table9.ifg_sii_id)) AS F
LEFT JOIN table10
ON F.risk = table10.risk AND C.v_type = table10.v_type
AND F.series = table10.series
This statement fails. But when I remove one the following two join-conditions in the last Left JOIN, it works as intended:
F.risk = table10.risk and/or C.v_type = table10.v_type
They are both of type CHAR, whereas series is type TINYINT, I guess it has something to do with joining on multiple conditions with strings, but I'm not able to find a workaround, any ideas?
according to your current SQL, Table C is not visible as it's a sub query within F. instead of C.v_type you need to use F.c_v_type and the c_v_type field must come from C table like. select v_type as c_v_type from table3... as C
In the last part of your Query You could try to actually select the table and include the Where Clause Like so:
LEFT JOIN (Select * from table10 Where C.v_type = v_type AND F.series = series) as xx
ON F.risk = xx.risk
Hope this helps

SQL update statement inserting PeopleID into child tables to link data

I need to place the PeopleID in several tables for my new database to link all of the peole information. I have tried several times to write a simple update statement please help. Every time I get close I get AMBIGUOUS COLUMN ERROR I don't know what else to do.
Update CONTRACT
Set PeopleID = B.PeopleID
from People A
Inner join
(
Select PeopleId, F.ContractID
From People A
Inner Join Person PRSN on PRSN.PersonID = A.PersonID
Inner Join DARPA_IMPORT_REAL..persnl oldP on oldP.pl_pid = PRSN.PersonID
Left outer join Contract F on F.ContractID = oldP.kn_254id
) B on A.PeopleID = B.PeopleID
Go
try this
Update CONTRACT Set CONTRACT.PeopleID = B.PeopleID
from People A
Inner join (
Select A.PeopleId, F.ContractID
From People AA
Inner Join Person PRSN on PRSN.PersonID = AA.PersonID
Inner Join DARPA_IMPORT_REAL..persnl oldP on oldP.pl_pid = PRSN.PersonID
Left outer join Contract F on F.ContractID = oldP.kn_254id ) B
on A.PeopleID = B.PeopleID
you were asigning the ´A´ alias twice so I recomend using different aliases always

How to turn this big query into a stored procedure

How can I turn this big query into a stored procedure and should I? What would the benefit be?
SELECT *
FROM user_items
LEFT JOIN items ON (items.item_id = user_items.item_id)
INNER JOIN item_categories ON (item_categories.item_id = items.item_id)
INNER JOIN item_subcategories ON (item_subcategories.item_id = items.item_id)
INNER JOIN brands ON (brands.brand_id = items.item_brand)
INNER JOIN item_photos ON (item_photos.item_id = items.item_id)
INNER JOIN place_items ON (place_items.item_id = items.item_id)
INNER JOIN places ON (places.place_id = place_items.place_id)
WHERE user_items.user_id = :user_id
from the brands table I only need the brand_name
from the places table I only need the place_name
The way I'm doing it right now, I'm getting all columns from brands and places, so a friend of mine told me I should probably consider using stored procedures
If you want columns from brands and items tables only, you can do like below
"SELECT brands.brand_name,places.place_name,
user_items.*,items.*,item_categories .*,
item_subcategories.*,item_photos.*,place_items.*
FROM user_items
LEFT JOIN items ON (items.item_id = user_items.item_id)
INNER JOIN item_categories ON (item_categories.item_id = items.item_id)
INNER JOIN item_subcategories ON (item_subcategories.item_id = items.item_id)
INNER JOIN brands ON (brands.brand_id = items.item_brand)
INNER JOIN item_photos ON (item_photos.item_id = items.item_id)
INNER JOIN place_items ON (place_items.item_id = items.item_id)
INNER JOIN places ON (places.place_id = place_items.place_id)
WHERE user_items.user_id = :user_id"
The use of stored procedure is to reuse a set of SQL statements . The performance of stored procedure would be as good as the SQL statements it contains.
A better approach for better readability of your code is to use ALIASES for table names.
When to use SQL Table Alias
In my experience, stored procedures have been more trouble than they're worth, being inflexible and therefore more difficult to maintain than inline SQL, residing outside version control, and failing to provide much if any performance benefit. And in this case a stored routine doesn't seem necessary or beneficial, because your query doesn't demand an advanced feature, such as a cursor. For another discussion of advantages and disadvantages, see this post.
DELIMITER $$
DROP PROCEDURE IF EXISTS `ABC` $$
CREATE PROCEDURE `ABC`(IN UID LONG)
READS SQL DATA
BEGIN
SELECT *
FROM user_items
LEFT JOIN items ON (items.item_id = user_items.item_id)
INNER JOIN item_categories ON (item_categories.item_id = items.item_id)
INNER JOIN item_subcategories ON (item_subcategories.item_id = items.item_id)
INNER JOIN brands ON (brands.brand_id = items.item_brand)
INNER JOIN item_photos ON (item_photos.item_id = items.item_id)
INNER JOIN place_items ON (place_items.item_id = items.item_id)
INNER JOIN places ON (places.place_id = place_items.place_id)
WHERE user_items.user_id = UID
END $$
DELIMITER ;
you can do like this and execute this and can call then :-
CALL ABC(1234);
where 1234 is user_id of user. Thank you