I created a function that searches for a particular value by priority. That is to say, if I found him then I would return the answer. If not continue to search in another way.
The problem is that the function, even if it finds an object at the beginning, does all the following SELECT's and does not stop at the first and returns it only.
CREATE FUNCTION GetId
(@A NVARCHAR(9),
@B NVARCHAR(9),
@C NVARCHAR(2)
)
RETURNS INT
AS
BEGIN
DECLARE @ResId INT = NULL
SET @ResId = (SELECT TOP 1 id
FROM MyTable
WHERE (Filed1 = @A AND Filed2 = @B
OR Filed1 = @B AND Filed2 = @A)
AND Filed3 = @C
AND Filed4 = 1)
IF @ResId != NULL
RETURN @ResId
ELSE
SET @ResId = (SELECT TOP 1 id
FROM MyTable
WHERE (Filed1 = @A OR Filed2 = @A)
AND Filed3 = @C
AND Filed4 = 1)
IF @ResId != NULL
RETURN @ResId
ELSE
SET @ResId = (SELECT TOP 1 id
FROM MyTable
WHERE (Filed1 = @B OR Filed2 = @B)
AND Filed3 = @C
AND Filed4 = 1)
IF @ResId != NULL
RETURN @ResId
RETURN @ResId
END