Search code examples
sqlin-subquery

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


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


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)