mssql and dynamic column from another table - sql-server

i have this select statement:
select * from folder
inner join subprops on folder.id = subprop.id
inner join props on props.id = subprops.id
inner join products on product.feature = subprop.val
product.feature has values for example 300,301
and subprop.val has these values as well
i have column props.colname
and i want to make the third inner join dynamicly by the props.colname value
with some kind of eval() or anything else
inner join products on product.eval(props.colname) = subprop.val
can you think about anything? i can't find solution for that without dynamic statement or loop - that i don't want to do

Related

Update Query with a few JOINs between tables and where clause

I have the following relations in MSSQL DB:
I want to make an UPDATE Query, where i can filter the first table values.
The example is as follows:
I want to get all Products from Inv_Transaction_Lines_Table, where Document_No from the first table(Gen_Documents_Table_1) is equal to '3250824' and State is 'Released'
The SELECT query is very simple:
SELECT dbo.Inv_Transaction_Lines_Table.*, dbo.Inv_Transaction_Lines_Table.Product_Id AS Expr1, dbo.Gen_Documents_Table.Document_No, dbo.Inv_Transaction_Lines_Table.Quantity_Base AS Expr2
FROM dbo.Gen_Documents_Table AS Gen_Documents_Table_1 RIGHT OUTER JOIN
dbo.Inv_Transactions_Table RIGHT OUTER JOIN
dbo.Inv_Transaction_Lines_Table ON dbo.Inv_Transactions_Table.Transaction_Id = dbo.Inv_Transaction_Lines_Table.Transaction_Id ON
Gen_Documents_Table_1.Id = dbo.Inv_Transactions_Table.Document_Id LEFT OUTER JOIN
dbo.Gen_Documents_Table ON Gen_Documents_Table_1.Master_Document_Id = dbo.Gen_Documents_Table.Id
WHERE (Gen_Documents_Table_1.State = N'30') AND (dbo.Gen_Documents_Table.Document_No = N'3250824')
but I cannot manage with the UPDATE query.
Thanks!
if your query for select is right ,you can use update on the same query for select .for example if you want update quantity_base :
update Inv_Transaction_Lines_Table set quantity_base = 'A'
FROM dbo.Gen_Documents_Table AS Gen_Documents_Table_1 RIGHT OUTER JOIN
dbo.Inv_Transactions_Table RIGHT OUTER JOIN
dbo.Inv_Transaction_Lines_Table ON dbo.Inv_Transactions_Table.Transaction_Id = dbo.Inv_Transaction_Lines_Table.Transaction_Id ON
Gen_Documents_Table_1.Id = dbo.Inv_Transactions_Table.Document_Id LEFT OUTER JOIN
dbo.Gen_Documents_Table ON Gen_Documents_Table_1.Master_Document_Id = dbo.Gen_Documents_Table.Id
WHERE (Gen_Documents_Table_1.State = N'30') AND (dbo.Gen_Documents_Table.Document_No = N'3250824')

Multiple INNER JOIN SELECT query not returning data

This is a stored procedure to select the full details of a wine.
It takes as a parameter a storage location ID.
This builds properly and is similar in structure to many sp's I have written that work,
however it returns no data. Is there something I am missing?
CREATE PROCEDURE [sp_retrieveInventory_Full]
(
#StorageLocationID [int]
)
AS
BEGIN
SELECT [WineName],
[RackID],
[RackColumn],
[RackRow],
[WineTypeID],
[WineVarietyID],
[VintnerName],
[dbo].[Vintner].[Country],
[dbo].[Vintner].[StateProvince],
[dbo].[Vintner].[Region],
[VendorName],
[Vintage],
[PurchaseDate],
[PurchasePrice],
[BottleSizeID],
[ABV],
[DrinkByDate],
[FoodType],
[TastingNotes],
[RatedBy],
[RatingScore]
FROM [dbo].[StorageLocation]
INNER JOIN [dbo].[Wine]
ON [dbo].[StorageLocation].[WineID] = [dbo].[Wine].[WineID]
INNER JOIN [dbo].[Vintner]
ON [dbo].[Vintner].[VintnerID] = [dbo].[Wine].[VintnerID]
INNER JOIN [dbo].[Vendor]
ON [dbo].[Vendor].[VendorID] = [dbo].[Wine].[VendorID]
INNER JOIN [dbo].[Pairing]
ON [dbo].[Pairing].[PairingID] = [dbo].[Wine].[PairingID]
INNER JOIN [dbo].[Rating]
ON [dbo].[Rating].[RatingID] = [dbo].[Wine].[RatingID]
WHERE [dbo].[StorageLocation].[StorageLocationID] = #storageLocationID
END
GO
When a query reruns no result it's because no records exists that satisfy the conditions in it's where clause, or, in case of queries that contains inner joins, at least one of the joins on condition returns no records.
The easiest way to figure out what join is messing up your query is to start removing the joins one by one, but to do that, you have to first change the select clause.
What I like to do is this: Start with all the joins except the last one - see if it returns any records:
SELECT 1
FROM [dbo].[StorageLocation]
INNER JOIN [dbo].[Wine]
ON [dbo].[StorageLocation].[WineID] = [dbo].[Wine].[WineID]
INNER JOIN [dbo].[Vintner]
ON [dbo].[Vintner].[VintnerID] = [dbo].[Wine].[VintnerID]
INNER JOIN [dbo].[Vendor]
ON [dbo].[Vendor].[VendorID] = [dbo].[Wine].[VendorID]
INNER JOIN [dbo].[Pairing]
ON [dbo].[Pairing].[PairingID] = [dbo].[Wine].[PairingID]
-- INNER JOIN [dbo].[Rating]
-- ON [dbo].[Rating].[RatingID] = [dbo].[Wine].[RatingID]
WHERE [dbo].[StorageLocation].[StorageLocationID] = #storageLocationID
If not, comment out the next join and run the query again. Rinse and repeat.
Please note, however, that there might be more than one inner join that prevents the query from returning records.

SQL Server - using Over/Partition By in complex query

We have many complex queries which involve a lot of columns and joins (see the example below) that are implemented as views.
In some cases these queries return duplicate rows which then have to be programmatically removed by the consuming app. Therefore, we would like to enhance the SQL query to eliminate the duplicates, and speed up the retrieval process.
I know that I can use OVER / PARTITION BY logic to do this, but I am not sure of how to modify the queries to obtain a working syntax.
Here is an example:
SELECT
Main.MfgOrder.OrderNumber,
Main.MfgOrder.DesignBOMID,
Main.Design_Plant.PlantID,
Main.MfgOrder_Operation.OrderOpID,
Main.MfgOrder_Operation.DesignOpID,
Main.MfgOrder_Operation.OpSeq,
Main.MfgOrder_Operation.Description,
Main.MfgOrder_Operation.CompletionStatus,
Main.MfgOrder__Shift.OrderShiftID,
Main.MfgOrder__Shift.WorkCenterMachineID,
Main.MfgOrder___Event.OrderEventID,
Main.MfgOrder____Reel.OrderReelID,
Main.MfgOrder____Reel.ReelNumber,
Main.MfgOrder____Reel.Location,
Main.MfgOrder____Reel.Test_Status AS Test_Status_Reel,
Main.MfgOrder____Reel.Test_Disposition AS Test_Disposition_Reel,
Main.MfgOrder____Reel.LabReleased,
Main.MfgOrder____Reel.ShipReelsBypassSet,
Main.MfgOrder_____Length.OrderLengthID,
Main.MfgOrder_____Length.LengthType,
Main.MfgOrder_____Length.LocationOnReel,
Main.MfgOrder_____Length.LocationOnLength,
Main.MfgOrder_____Length.TrialNumber,
Main.MfgOrder_____Length.SampleNumber,
Main.MfgOrder_____Length.PrintNumber,
Main.MfgOrder_____Length.Test_Status AS Test_Status_Length,
Main.MfgOrder_____Length.Test_Category,
Main.MfgOrder_____Length.Test_Disposition AS Test_Disposition_Length,
Main.MfgOrder_____Length.SampleSubmittedBy,
Main.MfgOrder_____Length.SampleSubmittedDate,
Main.MfgOrder_____Length.BypassTesting,
Main.MfgOrder_____Length_OperatorQty.Sample1Destination,
Main.MfgOrder_____Length_OperatorQty.Sample2Destination,
Main.MfgOrder_____Length_OperatorQty.Sample3Destination,
Main.MfgOrder______Component.OrderComponentID,
Main.MfgOrder______Component.DesignComponentID,
Main.MfgOrder______Component.ItemNo,
Main.MfgOrder_______Test.LabTestID,
Main.MfgOrder_______Test.OrderTestID,
Main.MfgOrder_______Test.TestComplete,
Main.MfgOrder_______Test.TestStatus,
Main.MfgOrder________Marker2.OrderMarkerID,
Master.Color.ColorName,
Master.LabTest.ExcludeFromPassFail,
CASE
WHEN Main.Design_Component.Component_Label IS NULL
THEN 'Unknown'
ELSE Main.Design_Component.Component_Label
END AS Component_Label
FROM
Main.MfgOrder
INNER JOIN
Main.Design__BOM ON Main.MfgOrder.DesignBOMID = Main.Design__BOM.DesignBOMID
INNER JOIN
Main.Design_Plant ON Main.Design__BOM.DesignPlantID = Main.Design_Plant.DesignPlantID
INNER JOIN
Main.MfgOrder_Operation ON Main.MfgOrder.OrderNumber = Main.MfgOrder_Operation.OrderNumber
INNER JOIN
Main.MfgOrder__Shift ON Main.MfgOrder_Operation.OrderOpID = Main.MfgOrder__Shift.OrderOpID
INNER JOIN
Main.MfgOrder___Event ON Main.MfgOrder__Shift.OrderShiftID = Main.MfgOrder___Event.OrderShiftID
INNER JOIN
Main.MfgOrder____Reel ON Main.MfgOrder___Event.OrderEventID = Main.MfgOrder____Reel.OrderEventID
INNER JOIN
Main.MfgOrder_____Length ON Main.MfgOrder____Reel.OrderReelID = Main.MfgOrder_____Length.OrderReelID
LEFT OUTER JOIN
Main.MfgOrder______Component ON Main.MfgOrder_____Length.OrderLengthID = Main.MfgOrder______Component.OrderLengthID
LEFT OUTER JOIN
Main.MfgOrder_______Test ON Main.MfgOrder______Component.OrderComponentID = Main.MfgOrder_______Test.OrderComponentID
LEFT OUTER JOIN
Main.MfgOrder________Marker2 ON Main.MfgOrder_______Test.OrderTestID = Main.MfgOrder________Marker2.OrderTestID
LEFT OUTER JOIN
Main.Design_Component ON Main.MfgOrder______Component.DesignComponentID = Main.Design_Component.DesignComponentID
LEFT OUTER JOIN
Master.Color ON Main.MfgOrder______Component.TapeColorID = Master.Color.ColorNumber
LEFT OUTER JOIN
Master.LabTest ON Main.MfgOrder_______Test.LabTestID = Master.LabTest.LabTestID
LEFT OUTER JOIN
Main.MfgOrder_____Length_OperatorQty ON Main.MfgOrder______Component.OrderLengthID = Main.MfgOrder_____Length_OperatorQty.OrderLengthID
you can use row_number as below: Below query will not select duplicate only on OrderNumber, if you need to add other columns you add accordingly
Select * from (
Select
RowN = Row_Number() over( partition by Main.MfgOrder.OrderNumber order by Main.MfgOrder.OrderNumber),
--- All your select columns and all your query with joins
) a
Where a.RowN = 1
Is the entire row duplicated exactly? If so then just add DISTINCT
SELECT DISTINCT
...
FROM
...
If you are getting duplicate rows where most columns the same but some columns are different then GROUP BY the columns that are the same and select MIN(column_name) for the ones that are causing the extra rows to appear.

groupby in view of sql returns aggregate error

I am trying to create a view with this query as you can see here:
SELECT dbo.Lines.LineNumber, dbo.Lines.DocumentNumber, dbo.Joints.JointNumber, dbo.Joints.JointSize, dbo.Joints.ShopField, dbo.Joints.WPS, dbo.WeldDetails.StateStep2 AS WeldState, dbo.Welds.WeldNumber,
dbo.FitUps.FitUpNumber, MAX(dbo.WeldDetails.Id) AS WeldDetailId, MAX(dbo.FitUpDetails.Id) AS FitupDetailId, dbo.Joints.Id AS JointId, dbo.Ends.Name, dbo.Joints.THK, dbo.FitUpDetails.StateStep2 AS FitupState,
dbo.Joints.Revision, dbo.Joints.Note
FROM dbo.FitUps INNER JOIN
dbo.Welds INNER JOIN
dbo.Joints INNER JOIN
dbo.WeldDetails ON dbo.Joints.Id = dbo.WeldDetails.JointId INNER JOIN
dbo.FitUpDetails ON dbo.Joints.Id = dbo.FitUpDetails.JointId ON dbo.Welds.Id = dbo.WeldDetails.WeldId ON dbo.FitUps.Id = dbo.FitUpDetails.FitUpId INNER JOIN
dbo.Lines ON dbo.Joints.LineId = dbo.Lines.Id INNER JOIN
dbo.Ends ON dbo.Joints.EndId = dbo.Ends.Id
GROUP BY dbo.Joints.Id
But when i want to save the view i get this error :
Here is a part of my data :
Every joint id can have multi fitupdetailid and welddetailid in my view i want just show the maximum value of fitupdetailid and welddetailid of my joint.
I rewrote your query with a more readable join structure than what your GUI spit out. This should run for you and fix your error. Whether the results are what you want or not depends on your data. You may also want to re-order the grouping to group how you want, hierarchically. But all of those columns will need to be in the grouping in one form or another.
SELECT
dbo.Lines.LineNumber,
dbo.Lines.DocumentNumber,
dbo.Joints.JointNumber,
dbo.Joints.JointSize,
dbo.Joints.ShopField,
dbo.Joints.WPS,
dbo.WeldDetails.StateStep2 AS WeldState,
dbo.Welds.WeldNumber,
dbo.FitUps.FitUpNumber,
MAX(dbo.WeldDetails.Id) AS WeldDetailId,
MAX(dbo.FitUpDetails.Id) AS FitupDetailId,
dbo.Joints.Id AS JointId,
dbo.Ends.Name,
dbo.Joints.THK,
dbo.FitUpDetails.StateStep2 AS FitupState,
dbo.Joints.Revision,
dbo.Joints.Note
FROM
dbo.FitUps
INNER JOIN dbo.FitUpDetails ON dbo.FitUps.Id = dbo.FitUpDetails.FitUpId
INNER JOIN dbo.Joints ON dbo.Joints.Id = dbo.FitUpDetails.JointId
INNER JOIN dbo.WeldDetails ON dbo.Joints.Id = dbo.WeldDetails.JointId
INNER JOIN dbo.Welds ON dbo.Welds.Id = dbo.WeldDetails.WeldId
INNER JOIN dbo.Lines ON dbo.Joints.LineId = dbo.Lines.Id
INNER JOIN dbo.Ends ON dbo.Joints.EndId = dbo.Ends.Id
GROUP BY
dbo.Lines.LineNumber,
dbo.Lines.DocumentNumber,
dbo.Joints.JointNumber,
dbo.Joints.JointSize,
dbo.Joints.ShopField,
dbo.Joints.WPS,
dbo.WeldDetails.StateStep2,
dbo.Welds.WeldNumber,
dbo.FitUps.FitUpNumber,
dbo.Joints.Id,
dbo.Ends.Name,
dbo.Joints.THK,
dbo.FitUpDetails.StateStep2,
dbo.Joints.Revision,
dbo.Joints.Note

Inner Join and Left Join in same sql query

I'm trying to perform inner join and then left join in same sql query.
But the left join is not working. It is not showing the null values
I've two tables EVENT_INVITATIONS and USERINFO which has 2 records when joined.
so, the join query goes like this :
select * from [UandMePROD].[dbo].EVENT_INVITATIONS EI
join [UandMePROD].[dbo].USERINFO UI on EI.USER_ID = UI.USER_ID and EI.EVENT_ID=11033
It gives out 2 records.
So, I'm performing a left join with another table CLIENT_CONTACTS which has only 1 matching record in it.
So, actually it should show the null value to the unmatched record. but it is not showing the second record. It is showing only 1 record which is matched(join)
My failed sql query :
select * from [UandMePROD].[dbo].EVENT_INVITATIONS EI
join [UandMePROD].[dbo].USERINFO UI on EI.USER_ID = UI.USER_ID
left join CLIENT_CONTACTS CC on UI.MOBILENO=CC.MOBILE_NUMBER
where cc.CLIENT_ID=20111 and EI.EVENT_ID=11033
can you please tell me where I'm doing mistake?
I need the 2 records.
Since you are doing a left join, cc.CLIENT_ID is null for all the values which only exist in CLIENT_CONTACTS and your where clause Where cc.CLIENT_ID = 20111
converts your LEFT JOIN into INNER JOIN. Adding this filter in ON clause solves the issue.
select *
from [UandMePROD].[dbo].EVENT_INVITATIONS EI
inner join [UandMePROD].[dbo].USERINFO UI on EI.[USER_ID] = UI.[USER_ID]
left join CLIENT_CONTACTS CC on UI.MOBILENO = CC.MOBILE_NUMBER
and cc.CLIENT_ID = 20111
where EI.EVENT_ID=11033
You should not specify EI.EVENT_ID on WHERE clause. Those limit your results after the join. You should specify EI.EVENT_ID in an ON clause.
select * from [UandMePROD].[dbo].EVENT_INVITATIONS EI join [UandMePROD].[dbo].USERINFO UI on EI.USER_ID = UI.USER_ID AND (EI.EVENT_ID=11033 or EI.EVENT_ID is null) left join CLIENT_CONTACTS CC on UI.MOBILENO=CC.MOBILE_NUMBER where cc.CLIENT_ID=20111
Providing some suggestions,since it is not possible to say what is happening with out table data
Left join should show null values from output of first inner join eventhough there are no mobile number matches,so try removing where condition and see if you are getting any result

Resources