Home > SQL > Join… without JOINs – The Joys of Temp Tables

Join… without JOINs – The Joys of Temp Tables

January 30, 2007

Okay, apparently I lose at SQL joins.  I spent a good long while (read: way too long) trying to mix and mash up three database tables to provide a slick LEFT JOIN output (I wanted the nulls to pump into a DataSet for select and updating).

Yeah, that didn’t work out so hot.  I’ll accept the fact that TSQL is still not my strongest skill—I’m past the SELECT * point, but not by a lot.  I much prefer to do the logic in C#… again, which I could have used managed objects if this was hitting a SQL 2005 box and not 2000.  But, I digress.


I had a table of questions.  I had a table of answers by report.  Think of this like a grade card (it was something similar, so I can related it that way).

To begin, I created a simple temporary table.

	(reportid int, 
	questionid int, 
	questiontext varchar(50), 
	sectionid int, 
	displayorder int, 
	answerid int)

Then, we’re ready to insert our questions into the table. The @variables are in place because this information will be coming in from a Stored Procedure.

INSERT #TempTable
	@reportid as 'int_reportid',
	' ' as ‘answerid

	Questions q,
	QuestionSections qs

	q.bool_active = 1 AND
	qs.sectionid = @sectionid AND
	qs.sectionid = q.sectionid
So, how do we populate that answerid column?  An UPDATE. 
UPDATE #TempTable
SET #TempTable.answerid = rr.answerid
FROM #TempTable t, ReportAnswers ra
(t.reportid = ra.reportid) AND
(t.questionid = ra.questionid)

So, that leaves our final steps of selecting (and returning) the TempTable, and then destroying it.

SELECT * FROM #TempTable

From here, save your stored procedure (or query) and run.

There’s one caveat that I’ve found.  The DataSet objects (XSD’s) in Visual Studio cannot read the columns.  This isn’t a ‘big’ deal if you’re just using these for the queries; however, it’s a hassle I’ve yet to work though.



Categories: SQL
%d bloggers like this: