SQL Server中的更新引发错误

时间:2016-09-29 07:04:47

标签: sql-server

我能插入一个字符串' 1989-06-18'到数据类型date的SQL Server列,但当我尝试使用' 2000-01-01'更新同一列时它抛出错误

  

System.Data.SqlClient.SqlException:从字符串转换日期和/或时间时转换失败。

这是我的更新查询

CREATE PROCEDURE sp_update
    @id int,
    @title varchar(4),
    @fname varchar(50),
    @lname varchar(50),
    @dob varchar(50),
    @location int,
    @address varchar(255),
    @mobile varchar(10),
    @email varchar(50),
    @experience int
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE ResumeMaster
    SET Title = @title,
        FirstName = @fname,
        LastName = @lname,
        DateOfBirth = @dob,
        Location = @location,
        Address = @address,
        mobileNo = @mobile,
        EmailAddress = @email,
        Experience = @experience,
        ModifiedDateTime = CURRENT_TIMESTAMP
    WHERE
        id = @id;
END

3 个答案:

答案 0 :(得分:0)

试一试。

CREATE PROCEDURE sp_update

    @id int,
        @title varchar(4),
        @fname varchar(50),
        @lname varchar(50),
        @dob varchar(50),
        @location int,
        @address varchar(255),
        @mobile varchar(10),
        @email varchar(50),
        @experience int
AS
BEGIN

    SET NOCOUNT ON;
    update ResumeMaster
                        set
                            Title = @title,
                            FirstName = @fname,
                            LastName = @lname,
                            DateOfBirth = Cast(@dob as Date),
                            Location = @location,
                            Address = @address,
                            mobileNo = @mobile,
                            EmailAddress = @email,
                            Experience = @experience,
                            ModifiedDateTime = CURRENT_TIMESTAMP
                        where id=@id;
END

答案 1 :(得分:0)

忽略关于将Varchar(50)投射到DateDateTime的答案 - 他们无法解决此问题。唯一的解释是您的字符串@dob不是有效日期。

这就是为什么要确保存储过程的参数与它们将要插入的字段匹配的原因。更改@dob参数以匹配字段的数据类型。

答案 2 :(得分:0)

使用 CAST ,将字符串指定为日期。

SELECT CAST('2000-01-01' AS Date) AS MyDate