How do you update a DateTime field in T-SQL?

后端 未结 8 1862
我寻月下人不归
我寻月下人不归 2021-01-30 08:05

The following query does not update the datetime field:

update table
SET EndDate = \'2009-05-25\'
WHERE Id = 1

I also tried it with no dashes,

8条回答
  •  天命终不由人
    2021-01-30 08:50

    Using a DateTime parameter is the best way. However, if you still want to pass a DateTime as a string, then the CAST should not be necessary provided that a language agnostic format is used.

    e.g.

    Given a table created like :

    create table t1 (id int, EndDate DATETIME)
    insert t1 (id, EndDate) values (1, GETDATE())
    

    The following should always work :

    update t1 set EndDate = '20100525' where id = 1 -- YYYYMMDD is language agnostic
    

    The following will work :

    SET LANGUAGE us_english
    update t1 set EndDate = '2010-05-25' where id = 1
    

    However, this won't :

    SET LANGUAGE british
    update t1 set EndDate = '2010-05-25' where id = 1  
    

    This is because 'YYYY-MM-DD' is not a language agnostic format (from SQL server's point of view) .

    The ISO 'YYYY-MM-DDThh:mm:ss' format is also language agnostic, and useful when you need to pass a non-zero time.

    More info : http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes

提交回复
热议问题