问题
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
回答1:
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)
回答2:
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))
)
来源:https://stackoverflow.com/questions/17552807/trying-to-delete-from-join-and-i-know-i-have-funky-spacing-and-i-know-i-have-dup