3

例如:

CREATE PROCEDURE dbo.MyProc
AS
BEGIN
  SET NOCOUNT ON;
  BEGIN TRY
    ...
    DECLARE @Id INT;

    -- I don't want the following line to throw and abort processing. 
    -- I just want @Id to remain NULL. I can add a nested TRY/CATCH, but is there
    -- a better way?
    SET @Id=(SELECT Id FROM MyTable WHERE ...); 
    ...
  END TRY
  BEGIN CATCH
    ...
  END CATCH;
END;

更新:澄清一下,如果返回多行,我希望 @Id 保持 NULL。

4

3 回答 3

3

我会做这样的事情来避免多行错误:

SELECT top 1 @Id = Id FROM MyTable WHERE ...

或这个

SELECT @Id = Id FROM MyTable WHERE ...
if @@rowcount > 1
   set @id = null

当有多行时,最后一块会将@Id 设置为空。

于 2012-07-18T18:41:48.023 回答
2

尝试这个:

select @id = (select max(id) from MyTable Where <YOUR CONDITION> Having count(1) = 1)

这将返回单行,如果有多个匹配则不返回任何行。

于 2012-07-18T18:59:11.897 回答
1

很确定这不会抛出:

SELECT @Id = Id FROM MyTable WHERE ...
于 2012-07-18T18:35:41.257 回答