Getting data from two tables not working SQL - sql

I am trying to get data from two tables based on a condition. Both tables has the same condition just the content change. B contains client data and A contain product data
I am using this this code for stored procedure
ALTER PROCEDURE [dbo].[printfatura]
#idfatura int
AS
SELECT DISTINCT *
FROM tbl_faturimi b, tblfaturimi_details a
WHERE b.ID_FATURES = #idfatura
AND a.NR_FATURES = #idfatura
If I choose the ID =2 then then I should take the result of 3 rows as much as the table has , but instead I am getting 6 row. Data are repeated or duplicate. In tables there is not duplicate or repeated data, but during the select query process I get repeated data.
What should I change in this code to make it work?
Thanks to everyone
The photos of data :https://www.sendspace.com/file/fk6c1u

Try this
ALTER PROCEDURE [dbo].[printfatura]
#idfatura int
AS
SELECT DISTINCT *
FROM tbl_faturimi inner join tblfaturimi_details a
ON b.ID_FATURES=a.NR_FATURES
WHERE b.ID_FATURES = #idfatura
AND a.NR_FATURES = #idfatura
OR
ALTER PROCEDURE [dbo].[printfatura]
#idfatura int
AS
SELECT DISTINCT *
FROM tbl_faturimi b, tblfaturimi_details a
WHERE b.ID_FATURES = #idfatura
AND a.NR_FATURES = #idfatura
AND b.ID_FATURES=a.NR_FATURES
As per the syntax When we try to join two table we have to write a ON clause which contains the matching columns of both tables.

Use inner join and group by clause.
SELECT A.*, B.*
FROM tbl_faturimi A
INNER JOIN tblfaturimi_details B
ON A.FEATURES = B.FEATURES
GROUP BY A.*, B.*;
Hope this helps. :)
ALTER PROCEDURE [dbo].[printfatura]
#idfatura int
AS
BEGIN
SELECT A.*, B.*
FROM tbl_faturimi A
INNER JOIN tblfaturimi_details B
ON A.fk_ID = B.pk_ID
GROUP BY A.SomeColumn
WHERE A.fk_ID = #idfatura
END;

Related

Rewrite query without using temp table

I have a query that is using a temp table to insert some data then another select from to extract distinct results. That query by it self was fine but now with entity-framework it is causing all kinds of unexpected errors at the wrong time.
Is there any way I can rewrite the query not to use a temp table? When this is converted into a stored procedure and in entity framework the result set is of type int which throws an error:
Could not find an implementation of the query pattern Select not found.
Here is the query
Drop Table IF EXISTS #Temp
SELECT
a.ReceiverID,
a.AntennaID,
a.AntennaName into #Temp
FROM RFIDReceiverAntenna a
full join Station b ON (a.ReceiverID = b.ReceiverID) and (a.AntennaID = b.AntennaID)
where (a.ReceiverID is NULL or b.ReceiverID is NULL)
and (a.AntennaID IS NULL or b.antennaID is NULL)
select distinct r.ReceiverID, r.ReceiverName, r.receiverdescription
from RFIDReceiver r
inner join #Temp t on r.ReceiverID = t.ReceiverID;
No need for anything fancy, you can just replace the reference to #temp with an inner sub-query containing the query that generates #temp e.g.
select distinct r.ReceiverID, r.ReceiverName, r.receiverdescription
from RFIDReceiver r
inner join (
select
a.ReceiverID,
a.AntennaID,
a.AntennaName
from RFIDReceiverAntenna a
full join Station b ON (a.ReceiverID = b.ReceiverID) and (a.AntennaID = b.AntennaID)
where (a.ReceiverID is NULL or b.ReceiverID is NULL)
and (a.AntennaID IS NULL or b.antennaID is NULL)
) t on r.ReceiverID = t.ReceiverID;
PS: I haven't made any effort to improve the query overall like Gordon has but do consider his suggestions.
First, a full join makes no sense in the first query. You are selecting only columns from the first table, so you need that.
Second, you can use a CTE.
Third, you should be able to get rid of the SELECT DISTINCT by using an EXISTS condition.
I would suggest:
WITH ra AS (
SELECT ra.*
FROM RFIDReceiverAntenna ra
Station s
ON s.ReceiverID = ra.ReceiverID AND
s.AntennaID = ra.AntennaID)
WHERE s.ReceiverID is NULL
)
SELECT r.ReceiverID, r.ReceiverName, r.receiverdescription
FROM RFIDReceiver r
WHERE EXISTS (SELECT 1
FROM ra
WHERE r.ReceiverID = ra.ReceiverID
);
You can use CTE instead of the temp table:
WITH
CTE
AS
(
SELECT
a.ReceiverID,
a.AntennaID,
a.AntennaName
FROM
RFIDReceiverAntenna a
full join Station b
ON (a.ReceiverID = b.ReceiverID)
and (a.AntennaID = b.AntennaID)
where
(a.ReceiverID is NULL or b.ReceiverID is NULL)
and (a.AntennaID IS NULL or b.antennaID is NULL)
)
select distinct
r.ReceiverID, r.ReceiverName, r.receiverdescription
from
RFIDReceiver r
inner join CTE t on r.ReceiverID = t.ReceiverID
;
This query will return the same results as your original query with the temp table, but its performance may be quite different; not necessarily slower, it can be faster. Just something that you should be aware about.

how can insert sql server stored procedure data to the new table?

I have following sql server stored procedure
SELECT
APO_Order_Id as Purchase_Order_Number,
CompanyID as Company_ID,
p.PJM_UserDefinedProjID as Project_ID,
case m.APO_Use_Alt_Address
end as Project_Site_Address, p.PJM_StartDate as Site_StartDate,
s.CNT_ClientName as Creditor,s.CNT_ABN as Creditor_ABN,s.CNT_UID as Creditor_Id,s.CNT_CreditorType as Creditor_Type, m.APO_Description as Purchase_Order_Description, isnull(d.Order_Amount,0) as Order_Total
FROM
Account_APOrderMaster m
left join
(
SELECT
APOD_Master_Id, APOD_Project_Id, sum(APOD_Total_Amount) as Order_Amount
FROM
Account_APOrderDetail
group by
APOD_Master_Id, APOD_Project_Id
) d on m.Ref_Code = d.APOD_Master_Id
left join Client_Name s on m.APO_Supplier_ID = s.Ref_Code
left join Project_Master p on d.APOD_Project_Id = p.ref_code
left join Client_Name pm on m.APO_ProjectManagerId = pm.Ref_Code
WHERE
apo_order_id = 00122975;
now I need insert data values of CompanyId to the table 'InvoiceMaster'. how can I insert CompanyID to the table?
If you have access to alter the stored procedure you can write insert command top of your query at procedure
INSERT INTO InvoiceMaster(Name of your column)
SELECT
CompanyID as Company_ID
FROM
Account_APOrderMaster m
LEFT JOIN
(SELECT
APOD_Master_Id, APOD_Project_Id,
SUM(APOD_Total_Amount) AS Order_Amount
FROM
Account_APOrderDetail
GROUP BY
APOD_Master_Id, APOD_Project_Id) d ON m.Ref_Code = d.APOD_Master_Id
LEFT JOIN
Client_Name s ON m.APO_Supplier_ID = s.Ref_Code
LEFT JOIN
Project_Master p ON d.APOD_Project_Id = p.ref_code
LEFT JOIN
Client_Name pm ON m.APO_ProjectManagerId = pm.Ref_Code
WHERE
apo_order_id = 00122975;
If you can't access the stored procedure code, it's better to write function for solve problems.
If you can't do that you should use ad-hoc distributed queries option in SQL Server
insert output of stored procedure in temp table
Or this link for solve your problems
insert stored procedure output to temp table

Accessing table returning by table-valued function from SP

I have table valued function
ALTER FUNCTION [dbo].[fn_Functiont]()
RETURNS TABLE
AS
RETURN
(
SELECT d.*, b.Name AS Name, ps.Name AS PaymentSystemName, c.UserName AS UserName, c.FirstName AS ClientFirstName, c.LastName AS LastName, c.Number AS DocumentNumber, c.Id
FROM Document AS d
JOIN System AS ps ON d.SystemId = ps.Id
JOIN Client AS c ON c.Id = d.ClientId
LEFT JOIN Shop AS b ON b.Id = d.ShopId
WHERE d.OperationTypeId IN (2, 4, 5) AND c.Type = 1
)
And SP. In that SP i have declared temporary table like this
DECLARE #tempTable AS TABLE
(
.. columns here ...
)
after declaring i just inserting info
INSERT INTO #tempTable
SELECT * FROM [dbo].[fn_Functiont]()
Select #column1,colum2...,from #tempTable
The problem is that i have to declare a lot of columns in #temptable and code looks like ugly.So is there a better way to reading rows in SP from table valued function?
Instead of table Variable #tempTable Use Temp Table and Try This
SELECT * INTO #tempTable FROM [dbo].[fn_Functiont]()

Query returns a different result every time it is run

This query always returns the same amount of rows but, in a different order, every time. Why does this happen?
I have more filters to add but I can't get past this step.
BEGIN
DECLARE #lastStatus Varchar(10)
SELECT
[Job].[Job],
[Job].[Part_Number],
[Job].[Rev],
[Job_Operation].[Description],
[Job].[Customer_PO],
[Job].[Customer_PO_LN],
[Delivery].[Promised_Date],
[Job_Operation].[Operation_Service],
[Job].[Note_Text],
[Job_Operation].[Status],
[Job_Operation].[Sequence]
INTO [#tmpTbl]
FROM [PRODUCTION].[dbo].[Job_Operation]
INNER JOIN [Job]
ON [Job_Operation].[Job]=[Job].[Job]
INNER JOIN [Delivery]
ON [Job_Operation].[Job]=[Delivery].[Job]
WHERE [Job].[Status]='Complete'
ORDER BY [Job_Operation].[Job],[Job_Operation].[Sequence]
SELECT *
FROM [#tmpTbl]
DROP TABLE [#tmpTbl]
END
Put the Order By on the Select * From #tmpTbl, not on the insert.
Hi you can do initials on your table and you can remove your bracket for non spaces so you can make your code shorter.
SELECT j.Job,
,j.[Part_Number]
,j.Rev
,j_O.Description
,j.Customer_PO
,j.[Customer_PO_LN]
,d.[Promised_Date]
,j_o.[Operation_Service]
,j.[Note_Text],
,j_o.Status,
,j_o.Sequence
,j.[Customer_PO],
,j.[Customer_PO_LN],
,d.[Promised_Date],
,j_o.[Operation_Service],
,j.[Note_Text],
,j_o.[Status],
[Job_Operation].[Sequence]
INTO [#tmpTbl]
FROM [PRODUCTION].[dbo].[Job_Operation] j_o
INNER JOIN Job j
ON j_o.Job = j.Job
INNER JOIN Delivery d
ON j_o.Job= d.Job
WHERE j.Status='Complete'
ORDER BY j_o.Job,j_o.Sequence
SELECT *
FROM [#tmpTbl]
DROP TABLE [#tmpTbl]
END
Because you don't have an order by clause when you select from #tmpTbl
Try
SELECT *
FROM [#tmpTbl]
ORDER BY Job, Sequence
You cannot specify the order data goes into a table through a SET command (i.e. SELECT INTO) - that is determined by whether the table has a clustered index defined after it's created.
You control the order of the data when you're eventually selecting FROM that table to get your results.
SELECT * FROM [#tmpTbl] ORDER BY ....

SQL: Select A when in A and not B or select B when in A and B

SQL is not my strong point and I am struggling to find a solution to this issue. I am trying to figure out how I can get a result set based on the following logic. Select record A when A is not in B OR select B if the record appears in B and A. I tried the following union which returns me all the records that match from the current day in the two tables but I cannot figure out how to pull the data I need from the two tables.
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE PurchaseOrderLine.dRequiredDate = convert(date, getdate())
UNION
SELECT 'b',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM GoodsIn
INNER JOIN PurchaseOrderLine
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE GoodsIn.dDateDelivered = getdate())
You can do a left outer join, and use a ISNULL or CASE statement in the select to return the required values.
I'll demonstrate:
SELECT
CASE WHEN b.iPurchaseOrderLineId IS NOT NULL THEN 'b' ELSE 'a' END AS [Source],
a.iPurchaseOrderLineId,
ISNULL(b.sProductDescription, a.sProductDescription) AS [sProductDescription]
FROM PurchaseOrderLine AS a
LEFT JOIN GoodsIn AS b ON a.iPurchaseOrderLineId = b.iPurchaseOrderLineId
AND b.dDateDelivered = GETDATE()
WHERE b.iPurchaseOrderLineId IS NOT NULL
OR a.dRequiredDate = CONVERT(DATE, GETDATE())
Hope that helps!
Hope This will help You: Just an example similar to you.
create table A(id int , name char(12))
go
create table B(id int , name char(12))
go
insert into A values (1,'ABC'),(3,'WXY')
insert into B values (1,'ABC'),(2,'AAA')
SELECT a.id,a.name FROM A EXCEPT SELECT * FROM B
UNION
SELECT a.id,a.name FROM A inner join b on a.id=b.id and a.name=b.name
Thanks!!!
If I understand you correctly, assuming GoodsIn=B, you may try something in this fashion.
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
LEFT JOIN GoodsIn
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE PurchaseOrderLine.dRequiredDate = convert(date, getdate())
AND GoodsIn.iPurchaseOrderLineId IS NULL
UNION
SELECT 'b',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM GoodsIn
INNER JOIN PurchaseOrderLine
ON PurchaseOrderLine.iPurchaseOrderLineId = GoodsIn.iPurchaseOrderLineId
WHERE GoodsIn.dDateDelivered = getdate());
You could also try literally as you described (assuming sProductDescription is in PurchaseOrderLine):
"Select record A when A is not in B"
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE iPurchaseOrderLineId NOT IN(SELECT iPurchaseOrderLineId FROM GoodsIn)
or in this way:
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
WHERE NOT EXISTS(SELECT * FROM GoodsIn
WHERE GoodsIn.iPurchaseOrderLineId=PurchaseOrderLine.iPurchaseOrderLineId)
or using EXCEPT:
SELECT 'a',PurchaseOrderLine.iPurchaseOrderLineId, sProductDescription
FROM PurchaseOrderLine
EXCEPT
SELECT 'a', iPurchaseOrderLineId, sProductDescription
FROM GoodsIn;
Just hints, tailor them to your needs.