You're confusing me by posting new questions on the same topic!
SQL Function that checks if a cdate is before or after a tdate[
^]
MSDN Create Function Documentation[^] [Edit - just spotted this one in Solution 1]
Fairly indepth treatise on functions[
^]
And the one possibly of most use as you seem to want to return a lot of data would be this codeproject article
Using Table-Valued Functions in SQL Server[
^]
[EDIT - translating the link that shows how to do this...]
You need to write the script to create a function as follows (change the names appropriately)
I've made some assumptions about what you want returned
CREATE FUNCTION MyFunction(@StartDate DATE, @EndDate DATE)
RETURNS @MyResults TABLE (
ContractID int NOT NULL,
LineNumber int NOT NULL,
ContractDate date NULL,
[Date] date NULL,
o.Name varchar(100) NULL,
[File] varchar(500) NULL,
DateAdded date NULL,
DateRemoved date NULL,
CTPS varchar(100) NULL,
[Branch Name] varchar(100) NULL,
YesNO varchar(3) NOT NULL
)
AS
BEGIN
-- remove DECLARE @StartDate DATE = '01/04/2013'
-- remove DECLARE @EndDate DATE = '30/04/2013'
INSERT INTO @MyResults
Then at the end put
RETURN;
END;
You may need to tidy up the NULL / NOT NULL declarations according to your own requirements and I'm not able to test this for syntax errors at the moment.
Run the script to create the function.
NOTE - in your sql you have
SELECT ... INTO [TPS]
but later you use
FROM [Temp].[dbo].[TPS] t
- these are not necessarily the same table. I would suggest explicitly using Temp.dbo.TPS OR #TMP to avoid any issues there.
Finally to call the function use something like
SELECT * FROM MyFunction(Date1, Date2);
Acknowledgement to Mika Wendelius for his article
Using Table-Valued Functions in SQL Server[
^] from which this solution is largely copied.