'创建程序'必须只是批量声明

时间:2017-12-15 10:14:41

标签: sql sql-server stored-procedures

enter image description here

CREATE PROCEDURE CleanupJob
    @NoDays int = 800
AS
BEGIN
    DECLARE @JobStartDateTime DATETIME = getutcdate()
    --Clean records older than 800 days 
    DECLARE @rowcount int

    SELECT @rowcount = 1

    WHILE @rowcount > 0 
    BEGIN
        DELETE top (100) [DB].[INSTANCE].[TABLE_DETAIL]
        WHERE [Event_ID] IN (SELECT [Event_ID] 
                             FROM [DB].[INSTANCE].[TABLE]
WHERE start_time <  DATEADD(day, -@NoDays, @JobStartDateTime)  
)


        SELECT @rowcount = @@ROWCOUNT
    END
END
GO 

它会抛出此错误

  

Msg 156,Level 15,State 1,Procedure CleanupJob,Line 14 [Batch Start   第19行]   关键字&#39; WHERE&#39;附近的语法不正确。

我不确定如何在proc propely下的delete语句中使用子查询。

编辑 -

start_time 列位于 [TABLE]

3 个答案:

答案 0 :(得分:1)

这个怎么样?

WHILE @rowcount > 0 
BEGIN
    DELETE TOP (100) [DB].[INSTANCE].[TABLE_DETAIL]
    WHERE [Event_ID] IN (
        SELECT [Event_ID] 
        FROM [DB].[INSTANCE].[TABLE]
        WHERE [start_time] <  DATEADD(day, -@NoDays, @JobStartDateTime)  

    SELECT @rowcount = @@ROWCOUNT
END

编辑:完成答案

GO
CREATE PROCEDURE CleanupJob
    @NoDays int = 800
AS
BEGIN
    DECLARE @JobStartDateTime DATETIME = GETUTCDATE()
    DECLARE @rowcount int = 1

    WHILE @rowcount > 0 
    BEGIN
        DELETE TOP (100) [DB].[INSTANCE].[TABLE_DETAIL]
        WHERE [Event_ID] IN (
            SELECT [Event_ID] 
            FROM [DB].[INSTANCE].[TABLE]
            WHERE [start_time] <  DATEADD(day, -@NoDays, @JobStartDateTime)  

        SELECT @rowcount = @@ROWCOUNT
    END  
GO 

答案 1 :(得分:1)

  

但我仍然得到CREATE PROCEDURE必须只是声明   错误

GO之前添加create proc。 您的程序似乎还有其他代码。

请注意,这不是错误,只是解析器突出显示。

如果您现在只选择并执行create proc代码,则不会出现此错误

答案 2 :(得分:0)

像这样:

DELETE A 
FROM [DB].[INSTANCE].[TABLE_DETAIL] A
where A.[Event_ID] IN 
             (SELECT [Event_ID] FROM [DB].[INSTANCE].[TABLE])
AND A.start_time <  DATEADD(day, -@NoDays,@JobStartDateTime)

您可以在此查询中添加TOP提示。