例如:
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。
答案 0 :(得分:3)
我会做这样的事情来避免多行错误:
SELECT top 1 @Id = Id FROM MyTable WHERE ...
或者
SELECT @Id = Id FROM MyTable WHERE ...
if @@rowcount > 1
set @id = null
当有多行时,最后一段将@Id设置为null。
答案 1 :(得分:2)
试试这个:
select @id = (select max(id) from MyTable Where <YOUR CONDITION> Having count(1) = 1)
如果有多个匹配,这将返回单行,或者不返回任何行。
答案 2 :(得分:1)
很确定这不会抛出:
SELECT @Id = Id FROM MyTable WHERE ...