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

自闭症网瘾萝莉.ら 提交于 2019-12-12 18:08:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!