1

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

4

6 回答 6

3

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.

于 2012-10-05T22:48:11.680 回答
1

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

于 2016-03-13T08:16:39.543 回答
0

You can just use "01" for the day:

INSERT INTO MyTable VALUES (1111, 'item_name', '19980901')
于 2012-10-05T22:44:57.590 回答
0

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]) ...

于 2012-10-05T22:48:29.590 回答
0

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.

于 2012-10-05T22:57:47.247 回答
0

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.

于 2012-10-05T22:59:59.477 回答