Trying to delete from Join and I know I have funky spacing and I know I have dup IMEI's

StackOverflow https://stackoverflow.com/questions/17552807

  •  02-06-2022
  •  | 
  •  

Question

DELETE dbo.bBoxDetail
FROM dbo.bBoxDetail AS BD
INNER JOIN dbo.bBoxHeader AS BH ON LTRIM(RTRIM(BD.bBoxDetailId)) = LTRIM(RTRIM(BH.bBoxId))
WHERE LTRIM(RTRIM(BD.ESNs)) = (SELECT LTRIM(RTRIM(IMEI)) FROM dbo.tmpIMEI)

I get this error:

Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

BD.ESNs is NVARCHAR(50) and IMEI is NVARCHAR(30) I have duplicate ESNs and I want to delete all ESNs that match the SELECT ... IMEI

Was it helpful?

Solution

If you read the error

Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Pay attention to Subquery returned more than 1 value as this is the error, you are returning any number of rows from your subquery:

The correct SQL is below:

DELETE dbo.bBoxDetail
FROM dbo.bBoxDetail AS BD
INNER JOIN dbo.bBoxHeader AS BH ON LTRIM(RTRIM(BD.bBoxDetailId)) = LTRIM(RTRIM(BH.bBoxId))
WHERE LTRIM(RTRIM(BD.ESNs)) = (SELECT TOP 1 LTRIM(RTRIM(IMEI)) FROM dbo.tmpIMEI)

OTHER TIPS

Use IN operator in WHERE clause

DELETE dbo.bBoxDetail
FROM dbo.bBoxDetail AS BD INNER JOIN dbo.bBoxHeader AS BH ON LTRIM(RTRIM(BD.bBoxDetailId)) = LTRIM(RTRIM(BH.bBoxId))
WHERE LTRIM(RTRIM(BD.ESNs)) IN (SELECT LTRIM(RTRIM(IMEI)) FROM dbo.tmpIMEI)

but preferred option is EXISTS operator

DELETE dbo.bBoxDetail
FROM dbo.bBoxDetail AS BD INNER JOIN dbo.bBoxHeader AS BH ON LTRIM(RTRIM(BD.bBoxDetailId)) = LTRIM(RTRIM(BH.bBoxId))
WHERE EXISTS (
              SELECT 1
              FROM dbo.tmpIMEI
              WHERE LTRIM(RTRIM(BD.ESNs)) = LTRIM(RTRIM(IMEI))
              )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top