2

I need to to extract the month from date time fieldA then put the result into fieldB as an integer in the same table IF fieldB is empty.

eg) 1988-02-03 00:00:00.000 I need to extract 02 and put the result into another field only if that field is empty.

I guess this will end up as a stored procedure.

2
  • "I need to extract 02" section is unclear, you;re updating two fields on any condition? Commented Mar 6, 2013 at 17:52
  • The answer here is more complete than the proposed duplicate question as it also covers how to update fields and check for empty fields. Commented Mar 7, 2013 at 11:31

3 Answers 3

8

Use MONTH()

UPDATE your_table SET some_column = MONTH(date_column) WHERE some_column IS NULL 
Sign up to request clarification or add additional context in comments.

1 Comment

... assuming that the 02 is actually the month and that the date format isn't YYYY-DD-MM
1

MONTH(fieldA) or DATEPART(M, fieldA)

Comments

1

SQL Server has a built-in function called month() that will return the month for date and timestamp data types

UPDATE yourtable SET newcolumn = month(columnname) WHERE newcolumn IS NULL 

2 Comments

It will not work on timestamp datatypes, since those don't really represent an actual date per se ....
As @marc_s commented, timestamp is not date or datetime. The name was such a huge confusion that they are deprecating it: The timestamp syntax is deprecated. This feature will be removed in a future version of Microsoft SQL Server.*

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.