加入临时表时遇到问题

时间:2017-02-17 19:38:54

标签: sql-server

我正在尝试将3个表连接到临时表中,但一直收到此错误:

  

Msg 2714,Level 16,State 6,Line 1
数据库中已经有一个名为'#SalesOrder_History'的对象。

以下是我正在尝试的内容:

CREATE TABLE #SalesOrder_History ([OrderDate] date, [DonutOrder_ID] int, [Customer_ID] int, [FirstName] VARCHAR(15), [LastName] VARCHAR(20), [StreetAddress] VARCHAR(20), [Apt] CHAR(3), [City] VARCHAR(15), [State] VARCHAR(15), [ZipCode] CHAR(5), [HomePhone] CHAR(10), [MobilePhone] CHAR(10), [OtherPhone] CHAR(10), [Qty] CHAR(3), [Donut_ID] INT, [DonutName] VARCHAR(10), [Description] VARCHAR(20), [UnitPrice] CHAR(5))
    SELECT Donut_Order.OrderDate, Donut_Order.DonutOrder_Id, Donut_Order.Customer_ID
    From Donut_Order
    FULL OUTER JOIN #SalesOrder_History AS SOH 
    ON Donut_Order.OrderDate=SOH.OrderDate
    FULL OUTER JOIN #SalesOrder_History AS SOH1
    ON Donut_Order.DonutOrder_Id=SOH1.DonutOrder_ID
    FULL OUTER JOIN #SalesOrder_History AS SOH13
    ON Donut_Order.Customer_ID=SOH13.Customer_ID

    UNION 
    Select Customers.FirstName, Customers.LastName, Customers.ApartmentNumber
    From Customers
    FULL OUTER JOIN #SalesOrder_History AS SOH2
    ON Customers.LastName=SOH2.LastName
    FULL OUTER JOIN #SalesOrder_History AS SOH12
    ON Customers.StreetName=SOH12.StreetAddress
    Full OUTER JOIN #SalesOrder_History AS SOH13
    ON Customers.ApartmentNumber=SOH13.Apt

    UNION 
    Select Customers.City, Customers.StateName, Customers.Zipcode
    From Customers
    FULL OUTER JOIN #SalesOrder_History AS SOH14
    ON Customers.City=SOH14.City
    FULL OUTER JOIN #SalesOrder_History AS SOH15
    ON Customers.StateName=SOH15.State
    FULL OUTER JOIN #SalesOrder_History AS SOH16
    ON Customers.Zipcode=SOH16.ZipCode

UNION 
    Select Customers.HomePhone, Customers.MobilePhone, Customers.OtherPhone 
    FROM Customers
    FULL OUTER JOIN #SalesOrder_History AS SOH17
    ON Customers.HomePhone=SOH17.HomePhone
    FULL OUTER JOIN #SalesOrder_History AS SOH18
    ON Customers.MobilePhone=SOH18.MobilePhone
    FULL OUTER JOIN #SalesOrder_History AS SOH19
    ON Customers.OtherPhone=SOH19.OtherPhone

    UNION 
    Select Donuts.Quanity, Donuts.Donut_Id, Donuts.DonutName
From Donuts
FULL OUTER JOIN #SalesOrder_History AS SOH20
    ON Donuts.Quanity=SOH20.Qty
FULL OUTER JOIN #SalesOrder_History AS SOH21
    ON Donuts.Donut_Id=SOH21.Donut_ID
FULL OUTER JOIN #SalesOrder_History AS SOH22
    ON Donuts.DonutName=SOH22.DonutName

UNION
Select Donuts.Donut_Description, Donuts.Price
From Donuts
FULL OUTER JOIN #SalesOrder_History AS SOH23
ON Donuts.Donut_Description=SOH23.Description
FULL OUTER JOIN #SalesOrder_History AS SOH24
ON Donuts.Price=SOH24.UnitPrice;

1 个答案:

答案 0 :(得分:4)

将其添加到您的陈述的开头:

if object_id(N'tempdb..#SalesOrder_History') is not null drop table #SalesOrder_History;

如果您在SSMS中的多个选项卡(会话)中摆弄这个问题,您可能已在另一个选项卡(会话)中创建了临时表,并且需要关闭该选项卡或从该选项卡中删除该表。