Select x.*, y.one, y.two
From x left join y on x.someid = x.someid
works fine
but
Select x.*, y.one, y.two
From x left join y on x.someid = x.someid
Where y=somevalue
does not work.
The solution is simple. Move where clause in join clause
Select x.*, y.one, y.two
From x left join y on x.someid = x.someid and y=somevalue
вторник, 25 септември 2007 г.
четвъртък, 20 септември 2007 г.
MSSQL 2000 Query results in random order
I have a web application displaying jokes. One of the functionalities it supports is showing a random joke.
I need the get the MSSQL server to randomize the jokes for me.
Here is my very simple solution:
SELECT *
FROM joke
ORDER BY NEWID()
Each execution generates different random results.
I need the get the MSSQL server to randomize the jokes for me.
Here is my very simple solution:
SELECT *
FROM joke
ORDER BY NEWID()
Each execution generates different random results.
четвъртък, 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
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
Абонамент за:
Коментари (Atom)