Storing just Month and Year in SQL Server 2008? - sql

Is it possible to save the month/year in SQL Server 2008 with a regular datetime? I don't need a time stamp and the column is going to store unique mo/yr combinations (i.e. 10-11, 11-11, 12-11, etc,.).
Any recommendations?

Without knowing the intended use, it is not possible to advise correctly. However, storing month and year is easily done in at least three ways:
use a date field, but always store into it the first day of the month at midnight; then always custom format the date field for display
add integer year and month fields, and populate them by splitting a date
add an integer field where you encode it as year * 100 + month or some other useful scheme

Sql Server will store the datetime data in its entirety (year-month-day hour:min:sec.milliSec) no matter what.
When you store your dates, you can make the day the 1st of the month. Just format the dates how you want when you do your queries.
http://www.sql-server-helper.com/tips/date-formats.aspx

From SQLServer 2008 and onwards:
Save as a Date column and add the following check constraint to make sure the value is always the first of the month:
datepart(month, MyDate)<>datepart(month,dateadd(day, -1, MyDate))

You cant only store year and month in a DateTime column. Well, what you can do is default the rest of the values. ie: 2011.10.1.1 , 2011.11.1.1 like that.
Or you can store it as string.

SELECT RIGHT(CONVERT(VARCHAR(10), GETDATE(), 105), 7) AS [MM-YYYY]
You should try this

Related

Selecting week / ISO week number from a date/time field

Sorry - this may be a basic question, but I have been banging my head against this for a week.
I have a database field with the format "dd/mm/yyyy hh:mm:ss" called UpdateTime and referencing max(AuditHistory.ActionedDateTime) in the database.
I am trying to identify the Week / ISO Week from the date part of this field only using the dataset in ReportBuilder3.
I am trying to achieve an integer entry in a column called "WeekNo" giving me the week of the year that a transaction was made so I can use this for grouping results by year | by week number on a report for senior management.
I have tried many combinations of:
,DATEPART(WEEK,DAY(max(AuditHistory.ActionedDateTime)) AS WeekNo and
,DATEPART(WEEK,MONTH(max(AuditHistory.ActionedDateTime)) AS WeekNo.
If I use a static date, e.g. , DATEPART(WEEK,DAY('1900-01-20')) AS WeekNo, it returns perfectly as "4" but I cannot for the life of me get the datepart format correct to identify the week from the format of the field.
I believe my issue is getting SQL to accept that the field is "dd/mm/yyyy hh:mm:ss" and work out the week from the date element.
Before I go mad - I thought I'd ask if there is a quick way to achieve this.
The DATEPART function expects a date / datetime / datetime2 value. You are passing in an integer representing the day or month number.
Assuming you're storing your dates correctly, you just need to pass in the date value directly:
DATEPART(WEEK, Max(AuditHistory.ActionedDateTime)) As WeekNo

SQL query to bring back list of servers from specific date range

I'm trying to make a query with SQL Server Management Studio 2017 that brings back a count of all the servers with a projected migration date of this year. I have one query made now, but it's still bringing back some servers with dates from years before.
SELECT MONTH(Projected) as [Month], count(*) as [Total]
FROM dbo.tFake
WHERE Projected >='01/01/2019' AND Projected <='12/31/2019
GROUP BY Month(Projected)
ORDER BY [Month]
Date format is mm/dd/yyyy btw. How can I get this query to bring back just servers that are projected for the year 2019?
Going by the assumption that your data type is wrong, the first step is to fix that.
Note, I am assuming that your data only contains dates, and not time (which your query implies). Firstly, you'll need to change the value of all your rows to an convertible value, we'll go with the ISO format yyyyMMdd:
UPDATE dbo.tFake
SET Projected = CONVERT(varchar(8),CONVERT(date,Projected,101),112);
Now that all the rows are a literal string in the format yyyyMMdd we can alter the column:
ALTER TABLE dbo.tFake ALTER COLUMN Projected date;
Now, we can run your query again, but now your data type is correct, you won't have the problem:
SELECT MONTH(Projected) as [Month], count(*) as [Total]
FROM dbo.tFake
WHERE Projected >= '20190101' AND Project < '20200101' --I prefer the >= and < method. This is especially import with date & time data types
GROUP BY Month(Projected)
ORDER BY [Month];
Notice the literal strings I passed are also in the yyyyMMdd format. If you must pass a literal string in the format MMddyyyy you can wrap in a CONVERT with the style code 101: CONVERT(date,'12/31/2019',101). 101 means the US style date (CAST and CONVERT (Transact-SQL).
Remember, this solution assumes you have date only values, and not date and time values. If you do (have date and time values) you'll want to use an appropriate date and time data type and use the ISO8601 style, instead of the ISO style.

is it possible to store m - m / Y formatted datetime with SQL Server

I need to store month - month / year formatted data in an SQL Server database. 01 - 12 / 2014 means, for instance, January 2014 to December 2014. Should I use varchar datatype or is it possible to do this with datetime datatype?
You cannot do this with a single date column in SQL Server. I would encourage you to store this as two date columns, such as: BeginDate and EndDate. That would be the best way to a period of time using native SQL types.
If you have to store this as a varchar(), then put the field in sensible order. Use a format like: 'YYYYMM-YYYYMM'. This allows each component to be parsed out easily and to be sorted by the first value. However, let me repeat my first advice: the best way to store a range of time is to use two columns, one for the start date and one for the end date.

Need to calculate date difference of today date vs converted date field

I have a table with a column that was previously converted using
(CONVERT(VARCHAR(19), GETDATE(), 112)
With the getdate being the date when the field was inserted. Now I have to compare the current date against the date the field was inserted.
The issue I'm facing is that when the date field is from last month, say 20131004, I calculate date difference by (CONVERT(VARCHAR(19), GETDATE(), 112) - 20131004, the result is 200. Obviously this is wrong...
Could you please suggest me how I could calculate the true date difference?
You should be using the DATE or DATETIME data type for that column. Why on earth would you ever store a date as a string? Do you know how much you lose by doing so? Validation, for one - a VARCHAR(19) column will accept 20131004 12:34 PM but will also accept nonsense values like I am not a date!.
If the data is actually good, you can simply do this instead of lazy shorthand and without any explicit conversions:
SELECT DATEDIFF(DAY, column_name, GETDATE()) FROM dbo.table;
If you get an error message with this, then you have bad data. You can identify it like this:
SELECT column_name FROM dbo.table WHERE ISDATE(column_name) = 0;
Please read:
Bad habits to kick : choosing the wrong data type
Bad habits to kick : mis-handling date / range queries
Bad Habits to Kick : Using shorthand with date/time operations
I agree with #Aaron that you should store a date field in a date field, not a text field.
If for some reason you do want to store it in a text field then the easiest way to calculate the number of days is to convert it back to a date field and then compare it:
SELECT DATEDIFF(DAY, CAST(column_name as DATETIME), GETDATE()) FROM dbo.table
This will throw an error if the value in the column cannot be converted to a date. You'll also need to make sure that the date is formatted correctly for your database. Assuming you use the format 112 you should be ok, but if you have the value 04/12/2013 in the column is that the 4th December 2013 or the 12th April 2013? It depends on how your database is configured.
But anyway, if you always insert dates in that field then you're nuts not making it a date field.
If you need to display the date somewhere then convert it on the way out.

Insert only Month and Year date to SQL table

I am using MS SQLServer and trying to insert a month/year combination to a table like this:
INSERT INTO MyTable VALUES (1111, 'item_name', '9/1998')
apparently, the above command cannot work since
Conversion failed when converting date and/or time from character string.
Because 9/1998 is a bad format. I want to fix this and this column of the table will show something like:
9/1998
12/1998
(other records with month/year format)
...
Can someone help me with this?
thank you
SQL Server only supports full dates (day, month, and year) or datetimes, as you can see over on the MSDN data type list: http://msdn.microsoft.com/en-us/library/ff848733(v=sql.105).aspx
You can use a date value with a bogus day or store the value as a string, but there's no native type that just stores month/year pairs.
I see this is an old post but my recent tests confirm that storing Date or splitting the year and month to two columns (year smallint, month tinyint) results in the overall same size.
The difference will be visible when you actually need to parse the date to the filter you need (year/month).
Let me know what do you think of this solution! :)
Kind regards
You can just use "01" for the day:
INSERT INTO MyTable VALUES (1111, 'item_name', '19980901')
You can:
1) Change the column type to varchar
2) Take the supplied value and convert it to a proper format that sql server will accept before inserting, and format it back to 'M/YYYY' format when you pull the data: SELECT MONTH([myDate]) + '/' + YEAR([myDate]) ...
You may want to consider what use you will have for your data. At the moment, you're only concerned with capturing and displaying the data. However, going forward, you may need to perform date calculations on it (ie, compare the difference between two records). Because of this and also since you're about two-thirds of the way there, you might as well convert this field to a Date type. Your presentation layer can then be delegated with the task of displaying it appropriately as "MM/yyyy", a function which is available to just about any programming language or reporting platform you may be using.
if you want use date type, you should format value:
declare #a date
SELECT #a='2000-01-01'
select RIGHT( convert (varchar , #a, 103), 7) AS 'mm/yyyy'
if you want make query like SELECT * FROM...
you should use varchar instead date type.