Understanding Table Valued Functions in SQL

  1. --Prepare Sample Data to work upon  
  2. CREATE TABLE MST_MyUsers  
  3. (  
  4.     Id int IDENTITY(1,1)  
  5.     ,Name nvarchar(100)  
  6.     ,CreatedDate datetime  
  7. )  
  8.   
  9. INSERT INTO MST_MyUsers VALUES ('Tony','2011-12-01')  
  10. INSERT INTO MST_MyUsers VALUES ('Sam','2012-04-01')  
  11. INSERT INTO MST_MyUsers VALUES ('James','2012-07-01')  
  12.   
  13. GO  
  14.   
  15. --Gets list of users created till specified date  
  16. CREATE FUNCTION [dbo].[udf_GetUserData]    
  17. (  
  18.     @CreatedDate datetime  
  19. )  
  20. RETURNS     
  21. @UserDetails TABLE     
  22. (    
  23.     Id int,    
  24.     Name nvarchar(50),    
  25.     CreatedDate datetime    
  26. )    
  27. AS    
  28. BEGIN    
  29.     --Returning sample data  
  30.     --In practical scenarios, we will have this data coming from a existing table or from logical computation  
  31.     INSERT INTO @UserDetails   
  32.     SELECT Id,Name,CreatedDate  
  33.     FROM MST_MyUsers  
  34.     WHERE CreatedDate <= @CreatedDate  
  35.   
  36.     RETURN     
  37. END    
  38. GO  
  39. ------------------------------------------------------------    
  40.   
  41. --Select users created upto 01 Jan 2011  
  42. SELECT * FROM udf_GetUserData('2011-01-01')  
  43.   
  44. --Select users created upto 01 Jan 2012  
  45. SELECT * FROM udf_GetUserData('2012-01-01')  
  46.     
  47. --Select users created upto 01 Jan 2013  
  48. SELECT * FROM udf_GetUserData('2013-01-01')  
  49.   
  50. ------------------------------------------------------------    
  51.   
  52. --Drop function created to get user details  
  53. DROP FUNCTION [udf_GetUserData]    
  54.   
  55. --Delete Sample data  
  56. DROP TABLE MST_MyUsers