Hi,
I have selected record based of person Birthday month. I have created SelectedPerson for preventing from repeated record.(i.e. if record exists in this table denotes that records already selected)
CREATE TABLE SelectedPersons([Month] INT,PersonId INT)
then created procedure to get records, below procedure gives records based on person birthday month and if its Id does not exists in SelectedPersons Table,if all the records from the Person table are inserted into SelectedPerson table,then it deletes all records form SeletcedPerson Table,and start the same process again
-- EXEC GETPesrsonsBasedOnBirthMonth 1
CREATE PROCEDURE GETPesrsonsBasedOnBirthMonth
@Month INT
AS
BEGIN
SET NOCOUNT ON;
IF (SELECT COUNT(Id) FROM PersonTable WHERE DATEPART(MONTH,BirthDay) = @Month) <> 0
BEGIN
GETPersons: -- This is GOTO Statement Label
SELECT TOP 3 *
INTO #temp
FROM PersonTable
WHERE DATEPART(MONTH,BirthDay) = @Month
AND Id NOT IN (SELECT PersonId FROM SelectedPersons WHERE [Month] = @Month)
ORDER BY NEWID()
IF (SELECT COUNT(Id) FROM #temp) > 0
BEGIN
INSERT INTO SelectedPersons
SELECT @Month,Id FROM #temp
END
ELSE
BEGIN
DELETE FROM SelectedPersons WHERE [Month] = @Month
DROP TABLE #temp
GOTO GETPersons
END
SELECT * FROM #temp
DROP TABLE #temp
END
END
GO
Screenshot