I am a C# developer learning SQL. I wrote the following scrip which works using temp tables.
But, as I understand it, temp tables are to be avoided.
Why should they not be used?
How should I rewrite this to not use temp tables?
To explain the sql, it gathers data from two different tables, then joins those two temp tables together and compares them. It basically finds the records in the first temp table that are not in the second one.
if object_id('tempdb..#pa') is not null
drop table #pa
Select dm.document_code, sm.segment_code
into #pa
from [dbo].[metadata_document_set] ds
join [dbo].[document_metadata] dm
on dm.metadata_document_set_id = ds.metadata_document_set_id
join segment_metadata sm
on dm.document_metadata_id = sm.document_metadata_id
where ds.code = 'PA'
and dm.code <> 'TEST'
and sm.not_in_spec = 0
if object_id('tempdb..#oh') is not null
drop table #oh
Select dm.document_code, sm.segment_code
into #oh
from [dbo].[metadata_document_set] ds
join [dbo].[document_metadata] dm
on dm.metadata_document_set_id = ds.metadata_document_set_id
join segment_metadata sm
on dm.document_metadata_id = sm.document_metadata_id
where ds.code = 'OH'
and dm.code <> 'TEST'
and sm.not_in_spec = 0
select * from #oh oh
left join #pa pa
on pa.segment_code = oh.segment_code and
pa.document_code = oh.document_code
where pa.document_code is null
order by oh.document_code, oh.segment_code
WITH. Common table expressions can directly replace your temporary tables (although the names would not start with#).