I have the following sql which returns Projects and related Contractors as well as document size info from three different tables. The sequence is: First Contractors are entered in the system, then Projects are entered for each Contractors, during with document sizes (sheets) are entered. So far so good: The following sql returns all projects along with appropriate Contractors and Sheets fine:
SELECT
dbo.generalcontractors.name,
dbo.Projects.*,
dbo.sheets.sheetsize,
dbo.sheets.sheetid
FROM
dbo.generalcontractors
INNER JOIN dbo.Projects ON (dbo.generalcontractors.uid = dbo.Projects.generalcontractorid)
INNER JOIN dbo.sheets ON (dbo.Projects.sheetid = dbo.sheets.sheetid)
ORDER BY
dbo.Projects.projectdate DESC
Now, what needs to happen is that documents for individual projects are entered in a ProjectDocuments table. I have the following code which checks to see documents exist in the ProjectsDocuments table and return appropriate values; currently, the project id is hard-coded and it work.
Question is: how can I combine the following sql into the sql above? I am looking for one query result which will show any matching rows from the ProjectsDocument table and if no matching then will show ‘Not Found’.
This is for SQL Server 2005.
Thanks!
IF (SELECT COUNT(*) FROM dbo.projectsdocuments, dbo.Projects
WHERE projectsdocuments.projectid = Projects.projectid
AND Projects.projectid = 5) > 0
SELECT *
FROM projectsdocuments
ELSE
SELECT 'Not Found' AS HighPrice
One option would be to just simply add the
ProjectDocumentstable to your query, using aLEFT OUTER JOIN.If there are no matching rows in the
ProjectDocumentstable – then all columns from that table will beNULL– so capturing one of the columns and using theISNULL(<colname>, 'Not Found')construction, you’d be displaying ‘Not Found’ when no values have been found inProjectDocuments:Two things I’d recommend doing:
use meaningful table aliases (like
gcforGeneralContractor,prforProjectand so forth) – it makes reading the queries just soooo much easier….explicitly specify the columns you want to to retrieve from the tables – that prevents unwanted surprises when suddenly your table has five BLOB columns more that get returned – even though you don’t need them!