Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Into Clause not working 1

Status
Not open for further replies.

phil22046

Programmer
Sep 12, 2001
154
US
I have a large SQL statement with a Union to another large SQL stmt. When I run it I see the data in the results pane of query analyzer. I want to put the results into a temp table to be able to write additional sql statements to update another table. Also to speed up execution I should index some of the fields. Everytime I try and place "INTO #tempfile" or a similar INTO .dbo.Temp_workfile" in the large SQL statement, I get an error.
 
This can be done, but before I show you how, let me ask you a question.

Do you understand the difference between Union and Union All?

When you use Union, sql server will only return distinct records. When you use Union All, sql server will return all the records, even if there would be duplicates.

Why is this important? Well... If you want to only insert distinct records in to the temp table, then you have to use a derived table. Like this...

[tt][blue]
Select Col1, Col2
Into #TempTable
From (
Select Col1, Col2 From SomeTable1
Union
Select Col2, Col2 From SomeTable2
) As SomeAlias
[/blue][/tt]

If you don't care about distinct records, or you know they will be distinct anyway, then you can do this...

Code:
Select Col1, Col2
Into   #TempTable
From   SomeTable1

Insert 
Into   #TempTable(Col1, Col2)
Select Col1, Col2
From   SomeTable2

Union All performs better than Union because sql server does not have to determine the distinct rows.

Make sense?


-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top