简体   繁体   中英

C# - SQL Server : Insert query with GETDATE() and Parameter

UPDATE:

I think the question is:

Why the command replace value of GETDATE() by DATE_CREATED parameter value although DATE_CREATED does NOT EXIST in command query?

I got the problem in Select statement as well...

How does GETDATE() work?

I'm having a problem with a SQL Server insert query.

I put GETDATE() into insert query, but I also put the parameter named DATE_CREATE with value 0001/01/01 as well.

And when I execute the insert query, it throw an exception

SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

Please help me figure out what cause this error.

P/s: Sorry about my bad English

Table create code:

CREATE TABLE [dbo].[USER](
    [USER_ID] [int] NOT NULL,
    [USER_NAME] [nvarchar](100) NOT NULL,
    [DATE_CREATED] [datetime] NOT NULL,

    CONSTRAINT [PK_USER] PRIMARY KEY CLUSTERED ([USER_ID] ASC)
) ON [PRIMARY]
GO

C# code:

    private void Working()
    {
        //Get a SQL Connection
        IDbConnection con = GetConnection();
        USER user = new USER();
        user.USER_ID = 1;
        user.USER_NAME = "User";
        user.DATE_CREATED = new DateTime(1, 1, 1);

        USERDao dao = new USERDao(con);
        con.Open();
        try{
            Insert(con,user);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        con.Close();
    }

    private int Insert(IDbConnection con,USER obj)
    {
        IDbCommand command;
        command = con.CreateCommand();
        string query = @"INSERT INTO USER (USER_ID, USER_NAME, DATE_CREATED) 
                          VALUES (@USER_ID, @USER_NAME, GETDATE())";
        command.CommandText = query +";";
        addDbDataParameter(command, "USER_ID", obj.USER_ID, DbType.Int32);
        addDbDataParameter(command, "USER_NAME", obj.USER_NAME, DbType.String);
        addDbDataParameter(command, "DATE_CREATED", obj.DATE_CREATED, DbType.DateTime);
        int res = command.ExecuteNonQuery();
        if (res == 0) { throw new Exception("Zero rows were affected."); }
        return res;
    }

    static public void addDbDataParameter(IDbCommand command, string name, object value, DbType dbType)
    {
        IDbDataParameter parameter = command.CreateParameter();
        parameter.DbType = dbType;
        parameter.Direction = ParameterDirection.Input;
        parameter.ParameterName = "@" + name;
        //parameter.SourceColumn = name;
        if (value == null) { parameter.Value = DBNull.Value; }
        else { parameter.Value = value; }
        command.Parameters.Add(parameter);
    }

As you can see, there is no parameter named DATE_CREATED in the insert query (it's GETDATE() value), but the command still add the value of user.DATE_CREATED .

P/s: I fixed it by removing addParameter DATE_CREATED from the command, and it worked.

I hope you can help me learn why it causes the issue... :(

The error message is very explicit about the range of valid dates:

"SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."

The minimum date value for the datetime data type is '1753-01-01'

If you really want to use '0001-01-01' then use datetime2 datatype, eg:

[DATE_CREATED] [datetime2] NOT NULL,

If what you really want is the minimum date supported by the SQL Server datetime datatype , then do as @Damith suggested and use

user.DATE_CREATED = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue

UPDATE : (the question is not clear):

USER , USER_ID , and(!) USER_NAME are all reserved words in SQL Server. Try:

    string query = @"INSERT INTO [USER] ([USER_ID], [USER_NAME], DATE_CREATED) 
                     VALUES (@USER_ID, @USER_NAME, GETDATE())";

I just created an empty table running your table create statement, and ran this command as TSQL successfully, eg

INSERT INTO [USER] ([USER_ID], [USER_NAME], DATE_CREATED) VALUES (1, 'joe', GETDATE())

MSSQL min date is different to c# DateTime.MinValue (1/1/0001) , try below,

 user.DATE_CREATED = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;

even though you are not using all the parameters in command parameter collection, it will be a validation for parameter values with the type you given. validation will fail with wrong input.

for example check below

var res =new System.Data.SqlTypes.SqlDateTime(1,1,1); //Invalid SqlDateTime.
 user.DATE_CREATED = new DateTime(1, 1, 1);

should be

 user.DATE_CREATED = DateTime.Now;

Why ?

As the error says :

"SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."

But you are setting the date to 0001/01/01 which will thow the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM