What does the third parameter in CONVERT() do? - sql-server-2008

Query
Get the Joining year,Joining Month and Joining Date from employee table
This is my query which I have to perform. For this I write the following script:
select
SUBSTRING (convert(varchar,joining_date,103),7,4) ,
SUBSTRING (convert(varchar,joining_date,100),1,3) ,
SUBSTRING (convert(varchar,joining_date,100),5,2)
from
EMPLOYEE
The result is: http://d.pr/i/vObI
But when I changed convert(varchar,joining_date,100) to convert(varchar,joining_date,101)
Result is like this: http://d.pr/i/G5fZ
Can anyone please explain what this parameter means?

There are several different ways that you can format date using convert(varchar.... These are well documented on the MSDN site or different sites online.
Using convert(varchar..., date, 100) places the date in the format:
mon dd yyyy hh:mmAM (or PM)
May 10 2013 12:55PM
Using convert(varchar...date, 101) puts the date in the format:
mm/dd/yyyy
05/10/2013
See Demo
My suggestion would be whenever you implement these conversions, be sure to give a length on the varchar(10), etc.
Based on what it looks like you are returning, you can eliminate some of the convert/substring statements that you are using and implement some other functions to get the same result:
select year(joining_date) as [year] ,
convert(varchar(3),joining_date,100) as [month] ,
day(joining_date) as [day]
from EMPLOYEE

I think there is a better approach to split and get datetime parts using DATEPART:
select DATEPART(YEAR, [joining_date]),
DATEPART(MONTH, [joining_date]),
DATEPART(DAY, [joining_date]) from EMPLOYEE
or if you are interested for example in names use DATENAME:
select DATEPART(YEAR, [joining_date]),
DATENAME(MONTH, [joining_date]),
DATEPART(DAY, [joining_date]) from EMPLOYEE
However according to MSDN for DATENAME: "The return value depends on the language environment set by using SET LANGUAGE".
Regarding your initial question - these parameters are basically styles or I would call them Regional specific codes as described here, and you can just run the different queries against the DB and you will see the strings returned - and you will figure why you get unexpected results. For more infos refer to MSDN: CAST and CONVERT

Related

MySQL query - check between two dates without needing to retrieve rows

I have a table that includes dates, I'm trying to check if a date I have falls between the dates in the table. My query is working, but it doesn't return anything. This seems like it should be very simple, but I can't wrap my head around it.
SQL query looks like this:
SELECT id FROM table
WHERE
(this_date) between (beginning_date_from_table) and (end_date_from_table)
The dates are generated dynamically in my script so I can ascertain if what I'm passing into it falls between the beginning and end dates in my table. I don't need any specific data from the table, just a boolean telling me whether the date is between the beginning and end dates or not.
You are looking for EXISTS:
SELECT
EXISTS(
SELECT id FROM table
WHERE
(this_date) between (beginning_date_from_table) and (end_date_from_table)
) AS hasValue
Hope this helps,
Check your MySQL server's date format and your generated date format.
MySQL date format is like that: '2019-01-30 18:19:52'
Also you can try change
(beginning_date_from_table) and (end_date_from_table)
to
(end_date_from_table) and (beginning_date_from_table)
Check: How do I query between two dates using MySQL?
I phrased the question slightly wrong, in that I was trying to return the result of a conditional. Once I realised how to ask google the right thing, I quickly came up with this solution:
SELECT (CASE WHEN this_date BETWEEN beginning_date AND end_date THEN 1 ELSE 0 END) AS date_result
Thanks to the other people who answered, your input put my thinking on the right track.

Converting Unix timestamp to actual Date and time

Is there any sql command which I can insert into the stated query so I can convert the timestamp. Although it could be done separately which I have seen so far but I am trying to find something which I can add to the stated query as that would be helpful because I am using other queries to retrieve the data as well. If you any other questions please do mention. Addition: rating_timestamp contains both time and date.
SELECT rating_id,
rating_postid,
rating_posttitle,
rating_rating,
rating_timestamp,
rating_username,
rating_userid
FROM wp_ratings;
In cases of date arithmetic, it is especially important to specify the DBMS you are using - Oracle's math is different from Postgres' math is different from SQL Server's math is different from MySQL's math is...
This assumes that you are using SQL Server. Since there is no built in command to do this conversion, you need to create your own function to do that. The function below takes a UNIX / Linux timestamp and converts it to an SQL Server datetime.
CREATE FUNCTION dbo.fn_ConvertToLocalDateTime (#unixdate BIGINT)
RETURNS DATETIME
AS
BEGIN
DECLARE #UTCTimeOffset BIGINT
,#LocalDatetime DATETIME;
SET #UTCTimeOffset = DATEDIFF(second, GETUTCDATE(), GETDATE())
SET #LocalDatetime = DATEADD(second, #unixdate + #UTCTimeOffset, CAST('1970-01-01 00:00:00' AS datetime))
RETURN #LocalDatetime
END;
GO
I wast sure about about Sql version before. This worked perfectly for me.
FROM_UNIXTIME(rating_timestamp,'%h:%i:%s %D %M %Y')

converting java time to sqldate in query

java datetime (date.getTime()) is stored as string in mysql field.
How can we convert this to sql date using sql query. I am using mysql database.
Is there any sql function available?
For example - This is stored (1416231812348) for today's date in db.
Thanks for suggestions.
Java is returning the date as a long, to convert it you can use:
SELECT FROM_UNIXTIME(event_time) FROM MY_TABLE
If you get an error, try the following (after testing, I can see that your data is stored in milliseconds so you need to use this method):
SELECT FROM_UNIXTIME(event_time/1000) FROM MY_TABLE
(Change event_time to be the field name in your table and MY_TABLE to be the table name.)
Here is a SQLFiddle example that shows it working.
Here is an answer that gives you formatting options as well:
http://notsoyellowstickies.blogspot.co.uk/2011/11/converting-long-into-datetime-mysql.html
There is a java.sql package, that has time included. You can send it straight into your database without needing to convert it.
This may be a more pre-emptive solution than converting a date string from Java, into time in MySQL.
A similar question was answered and may be able to help you out here:
A datetime equivalent in java.sql ? (is there a java.sql.datetime ?)
most probably you have recorded from:
System.currentTimeMillis()
so:
select DATE_FORMAT ( from_unixtime( your_table_field / 1000 ) , '%e %b %Y');
you can change the date format as you like.

mysql query not returning results

I am executing this query
SELECT *
FROM temp
WHERE DATE_FORMAT(startTime,'%m/%d/%Y') = '7/15/2012'
and startTime column has this value '2012-07-15 12:00:00'
But this is not returning any results. Can somebody please help?
Change here:
7/15/2012
to:
07/15/2012
According to the documentation for the DATE_FORMAT function, %m is "Month, numeric (00..12)". Note the zero-padding. So you need to write '07/15/2012' rather than '7/15/2012'.
(And in case you're wondering — I have no idea what month #0 is. So far as I'm aware, the months range from 01 to 12. Maybe some locales do have a month #0?)

DST to UTC append query creates a type conversion error in access

I have a table I'm using as a source for an append query that calls upon a table query, which calls upon a union query to effectively adjust the eastern prevailing time to spring forward and fall back while converting to utc. there are only three fields in the table but I keep getting "access did not import .... due to type conversion". Please Help Me out!!! Thank you in advance
below is the access sql:
{append query}
INSERT INTO somePrice ( price )
SELECT DTQuery.Price
FROM DTQuery
WHERE (((DTQuery.EPT)<>[2ndsunday]));
{DTQuery}
SELECT
TransposeQuery.Field3 AS [Zone]
, DateSerial(Left([field1],4),Left(Right([field1],4),2),Right([field1],2))+[TransposeQuery]![Hour]/24 AS EPT, Val([Field8]) AS Price
, DateValue(DateSerial(Year([EPT]),3,14))-(Weekday(DateValue(DateSerial(Year([EPT]),3,14)),1)-1)+3/24 AS 2ndSunday
, DateValue(DateSerial(Year([EPT]),11,7))-(Weekday(DateValue(DateSerial(Year([EPT]),11,7)),1)-1)+3/24 AS 1stSunday
FROM TransposeQuery
ORDER BY
TransposeQuery.Field3
, DateSerial(Left([field1],4),Left(Right([field1],4),2),Right([field1],2))+[TransposeQuery]![Hour]/24, Val([Field8]);
First some general stuff: If you want to convert between timezones, which involves adding or subtracting a number of hours you might want to use to DateAdd function.
DateAdd("h", -2, [SourceDateTime])
This simply takes two hours off the SourceDateTime field.
Also rather than using the Left(Right( combination you can use Mid(string, start, length)
Mid("1234567890", 2, 4)
Returns 2345, but if you are dealing with dates just use DatePart
DatePart("h", "17/12/2011 08:10")
Returns 8.
As for the type conversion error, it's hard to say as you haven't given us the types of the fields in the destination table.
If you run the append query without the first line this will rule out the destination table. If it still fails then it might be in the where clause, so move the fields into the results set and make sure they are the same type. If it still fails then it must be in the source query so check DTQuery opens without any problems.