I have following for validating a student number. If it is within my filering conditions, I would like to return the student number. I don't know how to execute the SELECT statement to get the number. Please help!

Thanks Sunita. I see what you are saying. Yes, I am trying to write portable function across servers/databases.RETURN(EXECUTE sp_executesql (@sql)) wouldn't work either as it returns 0 or 1 but I am trying to get the student number back.

Regarding the database references, you should consider using a synonym for the student table, rather than referencing the table by name. That way each server can use the same synonym but it would refer to their appropriate tables:

-- on PRODUCTION server:
CREATE SYNONYM Students FOR PRD.dbo.tblSTU
GO
-- on TEST server:
CREATE SYNONYM Students FOR TST.dbo.tblSTU
GO

I modified the date arithmetic to better utilize any existing indexes on the BirthDate column. It's also more precise if you're looking for students who are 23 years old or older, using DATEDIFF() in the original could have included some 22 year olds. And if it will always be 23 years prior to August 20, 2012, might as well hardcode it to August 20, 1989.