I have table ‘Images’ I want to get the main image if exist, and if not, get the first row in the table. I use this:
SELECT Students.Id, Images.ImagePath
FROM Students INNER JOIN
Images
ON Students.Id = Images.StudentId
AND ( (Images.IsMain = 1)
OR (Images.ImagePath = (
SELECT TOP(1) ImagePath
FROM Images
WHERE StudentId = Students.IdId)))
WHERE Students.Id = @StudentId
If there is no ‘IsMain’ in Images I get only one row, but if there is ‘IsMain’, I get the row twice.
Your problem is that you were selecting the IsMain image and the first image.
The following code selects the first row, which will be the IsMain one if it exists, otherwise the top row.