Reputation: 74470
For example:
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;
Update: Just to clarify, if multiple rows are returned, I want @Id to stay NULL.
Upvotes: 3
Views: 91
Reputation: 35663
Try this:
select @id = (select max(id) from MyTable Where <YOUR CONDITION> Having count(1) = 1)
This will return a single row, or no rows if there are multiple matching.
Upvotes: 2
Reputation: 2988
I will do something like this to avoid multiple rows errors:
SELECT top 1 @Id = Id FROM MyTable WHERE ...
or this
SELECT @Id = Id FROM MyTable WHERE ...
if @@rowcount > 1
set @id = null
This last piece will set the @Id to null when there were multiple rows.
Upvotes: 3
Reputation: 6921
Pretty sure this would not throw:
SELECT @Id = Id FROM MyTable WHERE ...
Upvotes: 1