I need to update a record IFF there is only one record matching my search criteria. Here’s what I have, but it’s crude:
DECLARE @TestCount INT;
SELECT @TestCount = COUNT(*)
FROM TestRecords tr
WHERE
tr.UnitSerial = @UnitSerial
AND
tr.PassFailStatus = 1;
IF (@TestCount = 1)
UPDATE
TestRecords
SET
Invalid = 1
WHERE
TestRecordID =
(SELECT TestRecordID
FROM TestRecords tr
WHERE
tr.UnitSerial = @UnitSerial
AND
tr.PassFailStatus = 1);
Of course this is example code – there are more restrictions and tables joins, etc in the SELECT statement, and it’s all wrapped by a transaction, but this is the gist of the stored proc logic.
I’m thinking there has to be a better way but I don’t know what that is. Any suggestions?
Thanks, Dave
You could do it in one query as:
This assumes you are using SQL 2005 or greater.