I want to simplify the following query :
INSERT INTO TP.VA(IDB,IDP,IDVS,IDVB)
SELECT
@IDB,@IDP,IDVIS,IDVTP
FROM
TP.VP
WHERE
IDP = @IDP AND
NOT EXISTS ( SELECT *
FROM TP.VA A
INNER JOIN TP.VP B
ON A.IDP=B.IDP
WHERE
A.IDB = @IDB
AND A.IDP = @IDP
AND A.IDVIS = IDVB
AND A.IDVD=IDVTP )
I would like to understand if it is possible to simplify it especially after the NOT EXISTS. How can I do it?
CodePudding user response:
You could 'simplify' the query by removing the join - it isn't needed.
INSERT INTO TP.VA(IDB,IDP,IDVS,IDVB)
SELECT
@IDB,@IDP,IDVIS,IDVTP
FROM
TP.VP B
WHERE
IDP = @IDP AND
NOT EXISTS ( SELECT *
FROM TP.VA A
WHERE
A.IDB = @IDB
AND A.IDP = B.IDP
AND A.IDVIS = B.IDVB
AND A.IDVD = B.IDVTP )