Monday 4 November 2013

Create MSSQL Table Function the Easy Way

Some times when you use Microsoft Products you find that they never quite get to the point and we require just a simple example, Nothing is more painful than trying to make head nor tail of the 'Create Table Valued Function' This is the garbage it provides.
-- ================================================
-- Template generated from Template Explorer using:
-- Create Inline Function (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:  
-- Create date: 
-- Description: 
-- =============================================
CREATE FUNCTION  
( 
 -- Add the parameters for the function here
 <@param1, sysname, @p1> , 
 <@param2, sysname, @p2> 
)
RETURNS TABLE 
AS
RETURN 
(
 -- Add the SELECT statement with parameter references here
 SELECT 0
)
GO

If I want to return a table this makes very little sense. At at time looks rather unclear. Do I use Angle Brakets when declaring variables '[id] '? Here's a short working example of the above.
CREATE FUNCTION [dbo].[SampleFunction]()
RETURNS @rtnTable TABLE
(
 [ID] uniqueidentifier null
)
AS
BEGIN


declare @sampleTable Table
(
 [ID] uniqueidentifier
)

insert into @sampleTable
select [stuffintosampletable]

insert into @rtnTable
select * from @sampleTable

Return

End