Question : Select Into and If Else

I get an error saying that #SalesHeader allready exists. The appears on the Else part even while it never gets to it.
Is this not permited in SQL?
Is there another to code this?
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
If Object_ID('#SalesHeader') Is Not Null
	Drop Table #xSalesHeader


If @DailyRouteDeliveryID Is Null 
	Select r.Route, dbo.Driver4RouteDate(h.DeliveryDate,h.RouteID) As Driver, h.InvoiceNumber 
	Into #SalesHeader 
	From tblSalesHeader h Join tblRoute r On r.RouteID = h.RouteID
	Where h.SalesHeaderID = @SalesHeaderID;
ELSE
	Select r.Route, dbo.DriverName(drd.DriverID) As Driver, h.InvoiceNumber 
	Into #SalesHeader
	From tblSalesHeader h Join tblDailyRouteDelivery drd On drd.DailyRouteDeliveryID = h.DailyRouteDeliveryID Join tblRoute r On r.RouteID = h.RouteID
	Where h.DailyRouteDeliveryID = @DailyRouteDeliveryID;

Answer : Select Into and If Else

Ok.. Try running this code twice or thrice and confirm whether you are receiving any errors or not..

If Object_ID('tempdb..#SalesHeader1') Is Not Null
        Drop Table #SalesHeader1
 
Create table #SalesHeader1 (SalesHeaderID int, CustomerID int, Route Varchar(50), Driver varchar(100),InvoiceNumber  varchar(7));  
 
If @DailyRouteDeliveryID Is Null  
INSERT into #SalesHeader1 (SalesHeaderID, CustomerID, Route, Driver ,InvoiceNumber )  
        Select h.SalesHeaderID, h.CustomerID, r.Route, dbo.Driver4RouteDate(h.DeliveryDate,h.RouteID) As Driver, h.InvoiceNumber  
        From tblSalesHeader h Join tblRoute r On r.RouteID = h.RouteID  
        Where h.SalesHeaderID = @SalesHeaderID;  
ELSE  
INSERT into #SalesHeader1 (SalesHeaderID, CustomerID, Route, Driver ,InvoiceNumber )  
        Select h.SalesHeaderID, h.CustomerID, r.Route, dbo.DriverName(drd.DriverID) As Driver, h.InvoiceNumber  
        From tblSalesHeader h Join tblDailyRouteDelivery drd On drd.DailyRouteDeliveryID = h.DailyRouteDeliveryID Join tblRoute r On r.RouteID = h.RouteID  
        Where h.DailyRouteDeliveryID = @DailyRouteDeliveryID;
Random Solutions  
 
programming4us programming4us