存储过程在调用时从不删除行

Stored procedure never deletes rows when called

在 SQL Server 2012 存储过程中,我有以下代码行执行以下操作:

我需要检查以确保 @galaxy 不为空,因为有时 table astroList.

中的列为 NULL

我没有任何错误,但没有任何内容被删除,我不确定为什么。

代码如下:

DECLARE @galaxyID UNIQUEIDENTIFIER

SET @galaxyID = (SELECT galaxyID FROM astroList WHERE astroID = @astroID)

DELETE FROM galaxyObjects 
WHERE galaxyID = @galaxyID AND @galaxyID IS NOT NULL

你不能真的使用SET @var = (SELECT ...),除非不可能 SELECT曾经 return 超过一行。因此,任何不了解数据模型的人在查看这段代码时都会认为这是一颗定时炸弹。 SQL 服务器中一个更安全的选择是使用带有连接的 DELETE (它适用于任意数量的行,并且在没有匹配时是 no-op):

DELETE go
  FROM dbo.astroList AS al
  INNER JOIN dbo.galaxyObjects AS go
  ON al.galaxyID = go.galaxyID
  WHERE al.astroID = @astroID;

这将忽略 astroListgalaxyID 为 NULL 的行。