尝试从COLUMN中删除数据

时间:2016-04-14 14:33:04

标签: sql-server

我试图摆脱所有CPAC_FR,如下所示

Facility Response   CPAC_FR Transfer Call        2016-03-07         1
Facility Response   CPAC_FR Fulfillment-Email   2016-03-04  4
Facility Response   CPAC_FR Fulfillment-Email   2016-03-10  1
Facility Response   CPAC_FR Fulfillment-Email   2016-03-17  2
Facility Response   CPAC_FR Fulfillment-Email   2016-03-21  2

这是我的代码。我还在学习如何编写查询,所以我不断陷入困境。

SELECT  SR_AREA, INS_PRODUCT, RESOLUTION_CD, CAST(CREATED AS DATE) AS DATEADD
      , COUNT(*) AS TOTAL
FROM    S_SRV_REQ WITH (NOLOCK)          
WHERE   (dbo.fn_dstoffset(CREATED) >= '3-1-2016')  
AND (dbo.fn_dstoffset(CREATED) <= DATEADD(D, 1, '3-31-2016'))  
AND  [SR_AREA] IS NOT NULL 
GROUP BY INS_PRODUCT, RESOLUTION_CD, SR_AREA,  CAST(CREATED AS DATE) 
ORDER BY SR_AREA,INS_PRODUCT,RESOLUTION_CD DESC

我更倾向于添加DELETE FROM .. WHERE ..

我使用的是Microsoft SQL Server Management Studio。

2 个答案:

答案 0 :(得分:1)

使用单个表时 - 一旦您的SELECT语句仅返回您要实际删除的数据,您就可以将'SELECT替换为DELETE并删除子句{ {1}}和GROUP BY。在你的例子中,你最终会得到这个:

ORDER BY

附注:

  • 考虑到FK约束,更新可能因约束而失败,或者可能会根据FK约束设置级联删除约束记录。
  • 建议始终首先在非生产设置中测试DELETE语句,以确保它们按预期运行。
  • 最后,让同事在生产环境中执行之前审查DELETE语句也绝不是一个坏主意。

修改

我假设DELETE FROM S_SRV_REQ WHERE (dbo.fn_dstoffset(CREATED) >= '3-1-2016') AND (dbo.fn_dstoffset(CREATED) <= DATEADD(D, 1, '3-31-2016')) AND [SR_AREA] IS NOT NULL 你的意思是Trying to delete data from a row 。您无法从行中删除数据,但如果该列允许可以为空的数据/值,则可以将行中的值更新为Trying to delete data from a。如果是这种情况,请相应更新您的问题。

答案 1 :(得分:1)

删除不适用于组 从选择开始,并确保这些是您要删除的行

SELECT  SR_AREA, INS_PRODUCT, RESOLUTION_CD, CAST(CREATED AS DATE) AS DATEADD
FROM    S_SRV_REQ        
WHERE   (dbo.fn_dstoffset(CREATED) >= '3-1-2016')  
AND     (dbo.fn_dstoffset(CREATED) <= DATEADD(D, 1, '3-31-2016'))  
AND     [SR_AREA] IS NOT NULL 

然后只需更改选择....行删除

DELETE 
FROM    S_SRV_REQ        
WHERE   (dbo.fn_dstoffset(CREATED) >= '3-1-2016')  
AND     (dbo.fn_dstoffset(CREATED) <= DATEADD(D, 1, '3-31-2016'))  
AND     [SR_AREA] IS NOT NUL