Been searching anywhere but I cant find any solution to my problem. I am working with SQL Server Compact Edition, Im using SQL Management Studio 2008 and dealing with time formats.
I want a datetime datatype returns a 12hour format. So far, I have this one:
SELECT
CONVERT(nvarchar(10), StartTime, 108) as timein
FROM TicketSales
It gives this result : 14:43:05
How can I achieve a 12 Hour format for this ? any help please?
Note: For SQL Server Compact Edition 2008
The closest I could come to an answer uses format mask 109:
SELECT
GETDATE() AS timestamp,
RIGHT(CONVERT(nvarchar(26), GETDATE(), 109), 14) AS time;
If you don't want those fractional seconds, then we can try using substring and concatenation:
WITH cte AS (
SELECT CONVERT(nvarchar(26), GETDATE(), 109) AS time
)
SELECT
time,
SUBSTRING(time, 13, 8) + RIGHT(time, 2) AS time
FROM cte;
You must use the right style, like 100
declare #mytime as Time = '14:00'
select CONVERT(varchar(15),#mytime,100)
=> 2:00pm
Original Answer:
converting-a-time-into-12-hour-format-in-sql
Related
I'm getting the above SQL error after executing this query.
SELECT r.SectionIDNum, r.PeopleIDNum, r.Completed, c.CourseID, s.DistrictIDNum, s.EndDate
FROM Registration r, Course c, Section s
WHERE r.SectionIDNum=s.SectionID AND c.CourseID=s.CourseIDNum AND r.Completed='Y'
AND s.EndDate between ('2012-06-31', 'yyyy-mm-dd') and ('2013-07-01', 'yyyy-mm-dd')
Apparently, the commas in the dates are causing the error but I don't know how to fix it.
June only has 30 days in it. So SQL Server is confused by your request to cast June 31 as a date.
This works fine:
SELECT CAST('2012-06-30' AS DATE)
One way to avoid end of month issues is to use the DATEADD() function, for example, to get one year and one day prior to July 1, 2013 like in your example:
SELECT DATEADD(day,-1,(DATEADD(year,-1,CAST('2013-07-01' AS DATE))))
Also, remember that BETWEEN is inclusive, so you're getting June 30 and July 1 in your example, perhaps just subtracting the year is sufficient.
Use the CAST() Function (CAST converts value of one data type to a different type. In this case, CHAR to DATETIME):
SELECT r.SectionIDNum
,r.PeopleIDNum
,r.Completed
,c.CourseID
,s.DistrictIDNum
,s.EndDate
FROM Registration r
,Course c
,Section s
WHERE r.SectionIDNum=s.SectionID
AND c.CourseID=s.CourseIDNum
AND r.Completed='Y'
AND s.EndDate BETWEEN CAST('20120630' AS DATETIME)
AND CAST('20130701'AS DATETIME)
You could also use:
CONVERT(DATETIME,'20130701')
How I may be able to Trim down Time DataType when retrieving from the database?
Value from the Database : 08:00:00.0000000
What I need : 08:00:00 only
I'm SQL Server 2008, VB.Net 2010
You're not really trimming (that's removing leading or trailing spaces), but any of these should work in SQL:
SELECT CAST(#YourValue as time(0))
or
SELECT LEFT(#YourValue, 8)
or
SELECT CAST(#YourValue as char(8))
I know there is a function called ISDATE to validate DATETIME columns, but it works only for the SMALLDATETIME and DATETIME types.
Is there a similar way to validate the new data type DATETIME2 in SQL Server 2008 and 2012?
In SQL Server 2012, you can use TRY_CONVERT:
SELECT TRY_CONVERT(DATETIME2, '2012-02-02 13:42:55.2323623'),
TRY_CONVERT(DATETIME2, '2012-02-31 13:42:55.2323623');
Results:
2012-02-02 13:42:55.2323623 NULL
Or TRY_PARSE:
SELECT TRY_PARSE('2012-02-02 13:42:55.2323623' AS DATETIME2),
TRY_PARSE('2012-02-31 13:42:55.2323623' AS DATETIME2);
(Same results.)
Sorry that I don't have a clever answer for you for < SQL Server 2012. You could, I guess, say
SELECT ISDATE(LEFT('2012-02-02 13:42:55.2323623', 23));
But that feels dirty.
TRY_CONVERT documentation on Microsoft Docs
TRY_PARSE documentation on Microsoft Docs
Be careful using the LEFT(..., 23) solution on database systems using another dateformat than mdy (and SQL-Server 2008). You can see the dateformat of the current session using the DBCC USEROPTIONS command.
On a database system using the german dateformat (dmy) the LEFT(..., 23) solution isn't working (detected on dates with day > 12). See the following test case:
-- test table using a DATETIME and DATETIME2 column.
CREATE TABLE dt_vs_dt2 (
dt DATETIME,
dt2 DATETIME2
);
-- set a datetime values with a day > 12.
DECLARE #date_value AS DATETIME = DATEADD(DAY, 18 - DAY(GETDATE()), GETDATE());
-- insert the current date into both columns using GETDATE.
-- note: using the following on a day > 12
INSERT INTO dt_vs_dt2 VALUES (#date_value, #date_value);
-- let's have a look at the values.
-- the values look the same (the datetime2 is more precise as expected).
SELECT dt, dt2 FROM dt_vs_dt2;
-- now we expect both values are valid date values.
-- to validate the datetime2 value, the LEFT(..., 23) solution is used.
SELECT ISDATE(dt), ISDATE(LEFT(dt2, 23))
FROM dt_vs_dt2;
How to solve that?
You can use a CAST(column_name AS DATETIME) instead of the LEFT(..., 23) to make this work:
-- using a CAST(... AS DATETIME) instead of `LEFT(..., 23)` seems to work.
SELECT dt, CAST(dt2 AS DATETIME) AS dt2
FROM dt_vs_dt2;
-- now both values are valid dates.
SELECT ISDATE(dt) AS dt, ISDATE(CAST(dt2 AS DATETIME)) AS dt2
FROM dt_vs_dt2;
demo on dbfiddle.uk (using dmy) / demo on dbfiddle.uk (using mdy)
On SQL Server 2012 and later you should use the TRY_PARSE / TRY_CONVERT solution described in #Aaron Bertrand answer. The CAST(... AS DATETIME) solution explained in this answer should also work.
I have a LINQ 2 SQL query that's getting me a list of results for the month of February 2012. The resulting where clause is
DECLARE #p0 DateTime = '2012-02-01 00:00:00.000'
DECLARE #p1 DateTime = '2012-02-29 23:59:59.999'
....
WHERE (CONVERT(DATE, [t0].[DatePlaced]) >= #p0) AND (CONVERT(DATE, [t0].[DatePlaced]) <= #p1)
When this runs I'm getting results for 3/1/2012 showing up as well as all the results for 2/2012.
If I change the where clause to use BETWEEN then the results only contain dates for February.
WHERE [t0].[DatePlaced] BETWEEN #p0 AND #p1
I'm using .net 4 and SQL Server 2008 R2 with and without SP1.
Switching the dates to 3/1/2011 and my query's end date to '2011-02-28 23:59:59.999' yielded the same results.
Is there another way to get the results for just 2/2012 aside from using BETWEEN which LINQ 2 SQL doesn't support?
.999 rounds up to midnight of the next day. You can check this:
DECLARE #p1 DateTime = '2012-02-29 23:59:59.999';
SELECT #p1;
What do you get?
Instead of trying to figure out the last instant of today (which will be different depending on the data type and precision), what you want instead is an open-ended date range:
DECLARE #p0 DATE = '2012-02-01',
#p1 DATE = '2012-03-01';
....
WHERE [t0].[DatePlaced] >= #p0
AND [t0].[DatePlaced] < #p1
Even easier would be to just pass in the starting date and say:
DECLARE #p0 DATE = '2012-02-01';
....
WHERE [t0].DatePlaced >= #p0
AND [t0].DatePlaced < DATEADD(MONTH, 1, #p0)
For some elaborate ideas about datetime best practices:
Bad habits to kick : mis-handling date / range queries
For some info on why BETWEEN (and by extension >= AND <=) is evil:
What do BETWEEN and the devil have in common?
If you need to select by month often, you could consider adding two computed columns to your table - one for the month, one for the year:
ALTER TABLE dbo.YourTable
ADD DatePlacedYear AS YEAR(DatePlaced) PERSISTED
ALTER TABLE dbo.YourTable
ADD DatePlacedMonth AS MONTH(DatePlaced) PERSISTED
Those two new columns are automatically computed by SQL Server, they're persisted (e.g. part of the table's storage), and you can even put an index on them, if that makes sense for you.
With those in place, you could now use a query like:
SELECT (columns)
FROM dbo.YourTable
WHERE DatePlacedYear = 2012 AND DatePlacedMonth = 2
to get all data from February 2012.
It's a classic space-vs-speed trade-off - by storing the two extra columns for each row, you need more space - but in return, querying gets easier and if you have an index on (DatePlacedYear, DatePlacedMonth), your queries should (ideally) be quite fast.
Instead of using AddMilliseconds(-1) try use AddMilliseconds(-3)
See this question how SQL Server treats the milliseconds
I have a table with two column as :
serial_number
1
2
3
dateOfAppoinement
2011-06-30 00:39:04.130
2011-06-30 00:40:01.130
2011-06-30 00:49:04.130
I want to get the highest serial_number of a day. I have to avoid the time part. I'm just using the date part.
Can anyone tell me how can I do this?
I updated my answer to use Convert like snkmchnb suggested. However in SQL Server 2008 there is a DATE datatype that is just the date portion of the year so you don't have to specify the 120 code. I tested this and it works perfectly and the SQL is pretty straight forward.
SELECT
MAX(serial_number),
CONVERT(DATE, dateOfAppointment) as [Day]
FROM
#TempSerialsByDate
GROUP BY
CONVERT(DATE, dateOfAppointment)
I think this select solves your problem, can't figure if it is the best way:
select dateadd(dd,0, datediff(dd,0, dateOfAppoinement ))
from your_table where serial_number = (select max(serial_number) form your_table)
How truncate date in sql server can be found here:
How can I truncate a datetime in SQL Server?