使用存储过程自动插入自上次插入后的秒数

pn9klfpd  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(316)

我有一张简单的table,像这样:

CREATE TABLE [dbo].[EolDatas]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ByteArray] [varbinary](250) NOT NULL,
    [InsertDate] [datetime2](7) NOT NULL,
    [CycleTime] [float] NOT NULL,

    CONSTRAINT [PK_EolDatas] 
        PRIMARY KEY CLUSTERED ([Id] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                          ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[EolDatas] 
    ADD CONSTRAINT [DF_EolDatas_InsertDate]  
        DEFAULT (GETDATE()) FOR [InsertDate]
GO

ALTER TABLE [dbo].[EolDatas] 
    ADD CONSTRAINT [DF_EolDatas_CycleTime]  
        DEFAULT ((0)) FOR [CycleTime]
GO

我想使用存储过程在bytearray列中插入值,如下所示:

CREATE PROCEDURE dbo.EolDatas 
    @byteArray varbinary(250) = NULL,
AS
    DECLARE @insertDate datetime2(7) = GETDATE()
    DECLARE @maxDate datetime2(7) = (SELECT MAX(dbo.EolDatas.InsertDate) 
                                     FROM dbo.EolDatas)
    DECLARE @cycleTime float = DATEDIFF(s, @maxDate, @insertDate)

BEGIN
    SET NOCOUNT ON;

    @cycleTime = SELECT MAX(InsertDate) FROM EolDatas;

    INSERT INTO dbo.EolDatas (ByteArray, InsertDate, CycleTime)
    VALUES (@byteArray, @insertDate, @cycleTime)
END

当我试图保存此过程时,出现以下错误:
消息156,级别15,状态1,程序EOLDATA,第6行[批处理开始行0]
关键字“as”附近的语法不正确。
消息102,级别15,状态1,程序EOLDATA,第16行[批处理开始行0]
“@cycletime”附近的语法不正确
你能帮我修一下这个程序吗?
我想从我的应用程序调用这个过程,传递bytearray,在插入行的过程中,数据库必须为 InsertDate 以及 Cycletime .

iecba09b

iecba09b1#

以下内容将解决您的问题,并向您展示sp的最佳实践。

CREATE PROCEDURE dbo.EolDatas 
(
    @byteArray varbinary(250) = NULL
)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @insertDate DATETIME2(7) = GETDATE(), @maxDate DATETIME2(7), @cycleTime INT; -- Don't use float unless you need to

    -- Assign a variable using a select
    SELECT @maxDate = MAX(InsertDate) FROM dbo.EolDatas;

    SET @cycleTime = DATEDIFF(s,@maxDate,@insertDate);

    -- This line appears to contradict what has come earlier
    -- @cycleTime=  Select Max(InsertDate) from EolDatas;

    INSERT INTO dbo.EolDatas (ByteArray, InsertDate, CycleTime)
    VALUES (@byteArray, @insertDate, @cycleTime);

    RETURN 0; 
END
GO

相关问题