DELETE Row of a table with a condition with another table - sql

I have the following SQL which is working,
IF NOT EXISTS(SELECT 1 FROM [Batch] B
INNER JOIN BatchProducts BP
ON (B.ID = BP.BatchID)
WHERE Bp.ID = #ID AND B.RetailerID = #RetailerID)
BEGIN
RETURN;
END
DELETE FROM BatchProducts WHERE BatchProducts.ID = #ID;
But it is composed with 2 statements. I want to use a single DELETE with a condition that RetailerID must match in BatchProducts table.

You can do it this way:
DELETE FROM BatchProducts
WHERE BatchProducts.ID = #ID
AND EXISTS (SELECT * FROM [Batch]
WHERE [Batch].ID = BatchProducts.BatchID AND [Batch].RetailerID = #RetailerID)

Is there a particular reason you need to check if it exists?
DELETE bp
FROM BatchProducts bp
JOIN Batch b
ON bp.BatchID = b.ID
WHERE bp.ID = #ID
AND b.RetailerID = #RetailerID

Related

If Else condition for temporary table

IF (#Track = 'SearchSelect')
BEGIN
IF(#limitedAccess = 'true')
BEGIN
SELECT CusLst.CustomerId, MAX(CusCon.CustomerContactId) AS CustomerContactId
INTO #CustomerList1
FROM CustomerList CusLst
LEFT JOIN CustomerContact CusCon ON CusLst.CustomerId = CusCon.CustomerId
INNER JOIN CustomerUser ON CusLst.CustomerId = CustomerUser.CustomerId
WHERE CustomerUser.UserId = #userId
GROUP BY CusLst.CustomerId
END
ELSE
BEGIN
SELECT CusLst.CustomerId, MAX(CusCon.CustomerContactId) AS CustomerContactId
INTO #CustomerList1
FROM CustomerList CusLst
LEFT JOIN CustomerContact CusCon ON CusLst.CustomerId = CusCon.CustomerId
GROUP BY CusLst.CustomerId
END
This is causing an error as customerList1 already exists. What to do if I want to fill temporary table based on the condition in my stored procedure?
Add this code before you start working
IF Object_id('tempdb..#CustomerList1') IS NOT NULL
BEGIN
DROP TABLE #CustomerList1
END
EDITED:
You probably have created your temp table either remove your create table or use
INSERT INTO #customerlist1(columns)
SELECT columns
FROM customerlist
since this
SELECT CusLst.CustomerId, MAX(CusCon.CustomerContactId) AS CustomerContactId
INTO #CustomerList1
FROM CustomerList CusLst
LEFT JOIN CustomerContact CusCon ON CusLst.CustomerId = CusCon.CustomerId
INNER JOIN CustomerUser ON CusLst.CustomerId = CustomerUser.CustomerId
WHERE CustomerUser.UserId = #userId
GROUP BY CusLst.CustomerId
creates a new temp table that's why it throws an error.
https://www.w3schools.com/sql/sql_select_into.asp
First check your temp table exists or not in your database.IF exists means drop your temp table and then create new one.
IF EXISTS(SELECT 1 FROM tempdb.dbo.sysobjects WHERE xtype in ('U') AND id =
object_id(N'tempdb..#CustomerList1') )
DROP TABLE #CustomerList1;

sql Update specific rows from select query

Hello I need some awful stored procedure and I cannot think of such
I've got these tables
Criterias
CriteriaId
Title
.......
Table StepCriterias
StepID
CriteriaId
OrderNum
Table Steps
StepID
ProcedureID
Title
...
So I select all the StepCriterias of a step with particular name and particular number
SELECT *
FROM StepCriterias sc
INNER JOIN Steps s ON sc.StepId = s.StepId
WHERE
s.Title = 'MYteststep'
ANd s.ProcedureId = 2
So suppose this query returns me five rows; now I should UPDATE all the resulting rows and their OrderNum should be incremented by 1 (I should increase the OrderNum of each row). That's my first problem and I cannot think of a stored procedure that an make that.
You could replace the join logic with an exsits condition in an update statement:
UPDATE StepCriterias sc
SET OrderNum = OrderNum + 1
WHERE EXISTS (SELECT *
FROM steps s
WHERE sc.StepId = s.StepId AND
s.Title = 'MYteststep' AND
s.ProcedureId = 2)
Probably this way .
UPDATE sc
SET OrderNum = OrderNum + 1
FROM StepCriterias sc
INNER JOIN steps s ON sc.StepId = s.StepId
WHERE s.Title = 'MYteststep'
AND s.ProcedureId = 2
In the event that you want an increment for each match, and a stepcriteria could match more than once, then:
UPDATE StepCriterias sc
SET OrderNum = (OrderNum +
(SELECT COUNT(*)
FROM steps s
WHERE sc.StepId = s.StepId AND
s.Title = 'MYteststep' AND
s.ProcedureId = 2
)
WHERE EXISTS (SELECT 1
FROM steps s
WHERE sc.StepId = s.StepId AND
s.Title = 'MYteststep' AND
s.ProcedureId = 2
);
There are simpler ways to express this in most databases, but the above is general syntax that should work in any database.
You can use UPDATE with a subquery, something like:
UPDATE StepCriterias
SET OrderNum = sc.OrderNum + 1
WHERE StepId IN (SELECT StepId
FROM StepCriterias sc
INNER JOIN steps s ON sc.StepId = s.StepId
WHERE s.Title = 'MYteststep' AND s.ProcedureId = 2);

Running slow with intersect

Trying to optimize a query it is updaing the records in table A based on the INTERSECT on two data sets.
UPDATE #TableA
SET IsFlag = CASE WHEN ISNULL(RJobFlag, 0) > 0 THEN 0 ELSE 1 END
FROM #TableA AS ABC
OUTER APPLY (
SELECT 1 RJobFlag
WHERE EXISTS (
SELECT ABC.COLUMN1,ABC.COLUMN2,ABC.COLUMN3,ABC.COLUMN4,ABC.COLUMN5,ABC.COLUMN6,ABC.COLUMN7,ABC.COLUMN8,ABC.COLUMN8,ABC.COLUMN9,ABC.COLUMN10,StudentID,SubjectID
INTERSECT
SELECT XYZ.COLUMN1,XYZ.COLUMN2,XYZ.COLUMN3,XYZ.COLUMN4,XYZ.COLUMN5,XYZ.COLUMN6,XYZ.COLUMN7,XYZ.COLUMN8,XYZ.COLUMN8,XYZ.COLUMN9,XYZ.COLUMN10,StudentID,SubjectID
FROM #TableB AS XYZ
WHERE XYZ.COLUMN1 = (SELECT DISTINCT ID FROM #TableC MNOP WHERE MNOP.StudentID = ABC.StudentID)
AND StudentID = ABC.StudentID
AND SubjectID = ABC.SubjectID )
) Subquery
WHERE ABC.COLUMN1= '2'
Appretiated if you have some ideas to better optimize it.
Thanks
This might be worse never know.
UPDATE tA
SET IsFlag = COALESCE(RJobFlag, 0)
FROM #TableA tA
LEFT JOIN ( SELECT 1 RJobFlag, *
FROM #TableB tB
WHERE EXISTS ( SELECT *
FROM #TableC tC
WHERE tC.ID = tB.COLUMN1 AND tC.StudentID = tB.StudentID)
) tB
ON tA.StudentID = tB.StudentID
AND tA.SubjectID = tB.SubjectID
AND tA.COLUMN1 = tB.COLUMN1
AND tA.COLUMN2 = tB.COLUMN2
AND tA.COLUMN3 = tB.COLUMN3
AND tA.COLUMN4 = tB.COLUMN4
AND tA.COLUMN5 = tB.COLUMN5
AND tA.COLUMN6 = tB.COLUMN6
AND tA.COLUMN7 = tB.COLUMN7
AND tA.COLUMN8 = tB.COLUMN8
AND tA.COLUMN9 = tB.COLUMN9
AND tA.COLUMN10 = tB.COLUMN10
If #TableA has a bunch of records and you're using outer apply or outer join every time you update it will be slow since it has to update every single record. maybe there's a way to only update the records that have changed?

Want to copy one column data into anothers table column in SQL...using this query its not working

UPDATE temp_test
SET country_i = (select a.country_code from temp_test2 a,temp_test c
where c.country_i is null and
a.active = 'A' and c.created_by = a.partner_by)
You could use a MERGE statement. It is easy to understand.
MERGE INTO temp_test t
USING temp_test2 u
ON (t.created_by = u.partner_by)
WHEN MATCHED THEN
UPDATE SET
t.country_i = u.country_code
WHERE t.country_i IS NULL
AND u.active = 'A';
UPDATE temp_test c SET country_i = (select a.country_code from temp_test2 a where a.active = 'A' and c.created_by = a.partner_by) where c.country_i is null;
In my mind it should work...

Update with two table ,I had a example for one row,but I must update 168432 rows,used sqlite

I want to update the sqlite table, the following is the example for updating one row:
update tpecroad set tnode = (SELECT b.nodeid FROM "TPECRoad" as a
join tpecnode as b
where pointn(a.geometry,numpoints(a.geometry)) = b.geometry and a.pk =1)
where pk=1
but there are 168432 rows to be updated, is there any faster way to update the large amount of the data?
It's like changed a.pk=1~168432 and pk=1~168432
Thanks a lots!!
update tpecroad as c
set tnode = ( SELECT b.nodeid
FROM "TPECRoad" as a join tpecnode as b
where pointn(a.geometry,numpoints(a.geometry)) = b.geometry and a.pk = c.pk);
If I understand the question right, this query may help:
update tpecroad a set tnode = (
select b.nodeid from tpecnode b
where pointn(a.geometry,numpoints(a.geometry)) = b.geometry
)
where exists (
select 1 from tpecnode b
where pointn(a.geometry,numpoints(a.geometry)) = b.geometry
);
Edit: If a.pk = b.pk must verify to perform the update, the query will look as follows:
update tpecroad a set tnode = (
select b.nodeid from tpecnode b
where pointn(a.geometry,numpoints(a.geometry)) = b.geometry
and a.pk = b.pk
)
where exists (
select 1 from tpecnode b
where pointn(a.geometry,numpoints(a.geometry)) = b.geometry
and a.pk = b.pk
);
Try this:
Update tpecroad a
set tnode = (SELECT b.nodeid
FROM tpecnode as b
where pointn(tpecroad.geometry,numpoints(tpecroad.geometry)) = b.geometry)