if exists(select * from sys.objects where name='get_current_state') drop function get_current_state; go create function get_current_state(@projectid uniqueidentifier) RETURNS varchar(30) as begin declare @current_state varchar(30) select top 1 @current_state = b.StepName from Projects a inner join ProjectsStep b on a.id=b.ProjectId where a.id=@projectid and StartTime<=(select GETDATE()) order by StepSort desc return @current_state end