четвъртък, 13 септември 2007 г.

Define a datatable sub set using a function in MSSQL Server

Lets have a Projects table which contains our projects.
In our queries we want to use sub set of that table data depends on some parameters, UserID for example. If the relation is simple it is easy, just add it in where clause.

We want to use that sub set in like a table

CREATE FUNCTION Func_UserProjects (@UserID int) RETURNS TABLE
as
RETURN ( SELECT Distinct p.*
From Projects p
Join ProjectPositions pp on p.ProjectID = pp.ProjectID
Join UsersOnProjectPositions up on up.ProjectPositionID = pp.ProjectPositionID
Where ((UserID = @UserID )

After definition we can use it in select statements for example

Declare @UserID int
Set @UserID int

Select *
FROM SceneComments sc WITH(NOLOCK)
Inner Join Scenes S WITH(NOLOCK) On S.SceneID = sc.SceneID
Inner Join Episodes E WITH(NOLOCK) On E.EpisodeID = S.EpisodeID
Inner Join Func_UserProjects(@UserID) P on P.ProjectID = E.ProjectID

Няма коментари: