将Datediff设置为存储过程中的变量

时间:2014-02-06 09:29:08

标签: sql variables stored-procedures datediff

我正在尝试将新假期插入我的假期表中,但我有一个持续时间列,我希望在存储过程中计算。我使用了日期差异来计算日期,但我想将日期差异声明为变量,然后将变量打印到insert语句的值中。随着下面的声明我不断得到这个错误: 在INSERT的SET子句或列列表中多次指定列名“StartDate”。在同一子句中不能为列分配多个值。修改子句以确保列只更新一次。如果此语句将列更新或插入到视图中,则列别名可以隐藏代码中的重复。

CREATE PROCEDURE    spRequestHoliday    @EmployeeID int,
                                    @StartDate date,
                                    @EndDate date,
                                    @Duration int

                /*
                Name: spRequestHoliday
                Description: Inserts a requested holiday into the holidays table
                */

AS

SELECT DATEDIFF(Day,@StartDate,@EndDate) AS DiffDate

BEGIN
    INSERT INTO Holidays(EmployeeID, StartDate, EndDate, Duration,StartDate)
    VALUES(@EmployeeID, @StartDate, @EndDate, 'DiffDate','PE')
END

2 个答案:

答案 0 :(得分:3)

试试这个

DECLARE @DateDiff AS Int

SELECT @DateDiff = DATEDIFF(Day,@StartDate,@EndDate)

INSERT INTO Holidays(EmployeeID, StartDate, EndDate, Duration, PE) --< columns name for PE
VALUES(@EmployeeID, @StartDate, @EndDate, @DateDiff,'PE')

OR

INSERT INTO Holidays(EmployeeID, StartDate, EndDate, Duration, PE) --< columns name for PE
VALUES(@EmployeeID, @StartDate, @EndDate, DATEDIFF(Day,@StartDate,@EndDate),'PE')

答案 1 :(得分:1)

在下面的陈述中,您已多次编写StartDate

INSERT INTO Holidays(EmployeeID, StartDate ,EndDate,持续时间, StartDate ) VALUES(@ EmployeeID,@ StartDate,@ EndDate,'DiffDate','PE')