试图结束存储过程

时间:2015-06-30 01:35:24

标签: sql-server stored-procedures

我是SQL Server新手,需要帮助才能完成存储过程。 这是代码:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF OBJECT_ID('spCopyPurchaseOrders') IS NOT NULL
    DROP PROC spCopyPurchaseOrders;

GO

CREATE PROC spCopyPurchaseOrders
AS

    IF OBJECT_ID('PurchaseOrders') IS NOT NULL
        DROP TABLE PurchaseOrders;
    SELECT *
    INTO PurchaseOrdersCopy
    FROM PurchaseOrders;

即使脚本顶部有一个有效的USE语句,我也无法识别数据库。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

在编码时,PurchaseOrders表在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

由于您使用的是SELECT...INTO,因此您可能需要PurchaseOrdersCopy

但是,这会更好

 -- 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;    

具体做法是:

a)尝试并在可以

时避免DROP和CREATE

b)使用架构名称(默认为dbo.)为对象名称添加前缀

关注:如果程序可以多次运行或由多人运行(dbo.PurchaseOrdersCopy共享),这将如何工作