Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a SQL Server table which contains 5 columns

The structure is as follows
-------------------------------------------
ID Month Emp_ID Count Year
-------------------------------------------
01 | Jan | 1 | 1.500 | 2015
02 | Feb | 1 | 1.500 | 2015
03 | Mar | 1 | 1.500 | 2015
04 | Apr | 1 | 1.500 | 2015
05 | May | 1 | 1.500 | 2015
06 | Jun | 1 | 1.500 | 2015
07 | Jul | 1 | 1.500 | 2015
08 | Aug | 1 | 1.500 | 2015
09 | Sep | 1 | 1.500 | 2015
10 | Oct | 1 | 1.500 | 2015
11 | Nov | 1 | 1.500 | 2015
12 | Dec | 1 | 1.500 | 2015

I want to convert the second column to like this
-------------------------------------------
ID Month Emp_ID Count Year
-------------------------------------------
01 | 31-Jan-2015 | 1 | 1.500 | 2015
02 | 28-Feb-2015 | 1 | 1.500 | 2015
03 | 31-Mar-2015 | 1 | 1.500 | 2015
04 | 30-Apr-2015 | 1 | 1.500 | 2015
05 | 31-May-2015 | 1 | 1.500 | 2015
06 | 30-Jun-2015 | 1 | 1.500 | 2015
07 | 31-Jul-2015 | 1 | 1.500 | 2015
08 | 31-Aug-2015 | 1 | 1.500 | 2015
09 | 30-Sep-2015 | 1 | 1.500 | 2015
10 | 31-Oct-2015 | 1 | 1.500 | 2015
11 | 30-Nov-2015 | 1 | 1.500 | 2015
12 | 31-Dec-2015 | 1 | 1.500 | 2015

Is there anyway to achieve this?
Posted

If you can do a count for all the days in a month and then replace the month name with the format you wanted?
 
Share this answer
 
You should not store month as string (varchar or anything like that); you should not store time-related data in the table with numeric and string attributes; it is quite unsupportable. Use appropriate data types, such as DATE. Then the particular form (string representation) of date/time data can be decided in your client code, not even SQL code.

—SA
 
Share this answer
 
If you're using SQL 2012 or higher, you can use the EOMONTH function[^] to get the last day in a month. Otherwise, starting from the first day in the month, adding one month and then subtracting one day will give you the same result.
SQL
SELECT
    -- SQL 2012:
    EOMONTH(Convert(date, Convert(char(4), Year) + '/' + Month + '/01')) As LastDayOfMonth
    
    -- Earlier versions:
    -- DateAdd(day, -1, DateAdd(month, 1, Convert(date, Convert(char(4), Year) + '/' + Month + '/01'))) As LastDayOfMonth
FROM
    YourTable

As Sergey said, don't store date values in a string column; use the date type[^] instead.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900