As coded, the PurchaseOrders
table is dropped before the SELECT
IF OBJECT_ID('PurchaseOrders') IS NOT NULL
DROP TABLE PurchaseOrders; -- <<< this breaks the SELECT FROM
SELECT *
INTO PurchaseOrdersCopy
FROM PurchaseOrders; -- <<< can't possible exist, the IF...DROP saw to it
And since you are using SELECT...INTO
, you probably mean PurchaseOrdersCopy
But, this would be much better
-- create an empty table, but just once, otherwise empty the existing table
IF OBJECT_ID('dbo.PurchaseOrdersCopy') IS NULL
SELECT *
INTO dbo.PurchaseOrdersCopy
FROM dbo.PurchaseOrders
WHERE 1=0
ELSE IF EXISTS (SELECT * FROM dbo.PurchaseOrdersCopy )
DELETE FROM dbo.PurchaseOrdersCopy; -- HINT: see if TRUNCATE TABLE dbo.PurchaseOrdersCopy is an option for you
-- this will be longer if you have an IDENTITY column
-- SET IDENTITY_INSERT ON (for example)
INSERT INTO dbo.PurchaseOrdersCopy
SELECT *
FROM dbo.PurchaseOrders;
Specifically:
a) try and avoid DROP and CREATE when you can
b) prefix your object names with schema name (dbo.
by default)
Concerns: how will this work if the procedure can be run more than once or by more than one person (dbo.PurchaseOrdersCopy is shared)