I have a varchar that is an 8 digit number and I need to convert to a datetime. The production number is an automatically generated number from when the time the order was placed. For example, the production number 10090203 is actually the datetime 2015-10-09 02:03:00. I need to cast a list of the varchar numbers into a datetime so that I can cross compare it to a list of date times. Here is how I convert datetime into varchar, but I am not sure how to go the other way around.
SELECT RIGHT('0' + CAST(DATEPART(M, table1.coldatetime) AS varchar), 2)
+ RIGHT ('0' + Cast(DATEPART(DD, table1.coldatetime) AS varchar), 2)
+ RIGHT('0' + CAST(DATEPART(HH, table1.coldatetime) AS varchar), 2)
+ RIGHT('0' + CAST(DATEPART(MINUTE, table1.coldatetime) AS varchar), 2)
AS 'CreatedNumber' FROM table1
This should work for you:
SELECT
DATEADD(mi,CAST(SUBSTRING(table1.coldatetime,7,2) AS INT),DATEADD(hour,CAST(SUBSTRING(table1.coldatetime,5,2) AS INT),CONVERT(datetime,'2015' + LEFT(table1.coldatetime,2)+SUBSTRING(table1.coldatetime,3,2))))
FROM
table1
Select
STR_TO_DATE(CONCAT('2015',coldatetime,'00'),'%y','%m','%d','%H','%i','%s')
From Table1
Related
select
traceid, CONVERT(varchar, CONVERT(VARCHAR(12),serialnumber)) serialnumber,
product_prod_week,
LEFT(product_prod_week,4)+'00' + month(dateadd(wk,right(product_prod_week,2) -1,
LEFT( product_prod_week,4) + '/01/01')) as product_prod_month,
isnull(product_prod_date,s.century_proddate) product_prod_date
from
mq m join serialdate s on m.product_prod_week= s.century_serdat
/*This part is restricting view to 36 months only*/
where
LEFT( product_prod_week,4)+'00' +month(dateadd(wk,right(product_prod_week,2) -1,
LEFT( product_prod_week,4) + '/01/01')) between substring(Replace(DATEADD(month,-37, DATEADD(month,-1,convert(date,getdate()))),'-',''),1,6)
and substring(replace(DATEADD(month,-1,convert(date,getdate())),'-',''),1,6)
The above is a view. view_mq. I have been banging my head over this from last many hours but can't find the issue.
select count(* )from view_mq
select COUNT(*) from view_mq where isdate(product_prod_date)=0
gives me this error -
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Where is the conversion happening? I don't understand.
serialdate table is has century_proddate column as datetime.
product_prod_date in mq is datetime format.
Rest are in char/varchar type.
I want to concatenate Date And Date Name Together. How Can I do it.
I need output like
2015-10-09 Friday
I got the DateName= `SELECT DATENAME(dw,'2015-10-09') as MyDateName`
Is it possible to make it in a single query?
Try this:
select CAST('2015-10-09' as varchar(10)) + ' ' +DATENAME(dw,'2015-10-09')
SQLFIDDLE DEMO
If your date is already in the varchar format then you dont need to CAST the date and simply try to concatenate them using +
select '2015-10-09' + ' ' +DATENAME(dw,'2015-10-09')
Since the value you provided is already a string, and DATENAME also returns a string, you can just concatenate together with +:
SELECT '2015-10-09 ' + DATENAME(WEEKDAY,'2015-10-09') as MyDateName
Assuming that in reality this is a parameter or a column of datatype datetime, you'll need to convert it to varchar first. There is no built in style for converting to varchar which contains the Day name, so you'll have to do the work yourself in two parts.
See MSDN page on cast and convert for the built in formats.
For the sake of my example, I'll create a datetime variable to use for tests:
DECLARE #d DATETIME; SET #d = '20151009';
Then to convert it to VARCHAR:
For the date part, ODBC is closest to the format you've asked for with the format yyyy-mm-dd hh:mi:ss(24h). So to get the date in that format as a varchar, you can use CONVERT with that style, value, 20.
SELECT CONVERT(VARCHAR(10), #d, 20)
Note I have converted it to VARCHAR(10) to truncate the timepart of the datetime that you don't want in the output. Then if you concatenate this with a space and the day name you already worked out, you can get your output:
SELECT CONVERT(VARCHAR(10), #d, 20) + ' ' + DATENAME(WEEKDAY, '2015-10-09') AS MyDateName
(Replace my variable with a column name and add a FROM statement if you're after output from a table)
You can try this code:
SELECT
CAST(CAST(GETDATE() AS DATE) AS VARCHAR) + ' ' + DATENAME(DW, GETDATE()) AS [DATE_WITH_WEEKNAME]
Data is following :
Code Article Amount Paid Balance
8001 Black 8000 7000 1000
I want to see it like this:
8001 (Black) (1000)
I think this is what you need.
Note : If you want to concatenate Numeric datatype data with varchar data then first you have to convert the numeric data into varchar type else you may get conversion failed error.
SELECT CONVERT(VARCHAR(30), Code) + ' (' + Article
+ ') (' + CONVERT(VARCHAR(30), Balance) + ')' new_column,
Article,
Amount,
Paid,
Balance
FROM <tablename>
In the BETWEEN documentation description (http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#operator_between) I've noticed a weird expression that I cannot understand entirely:
For best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.
So I have the following questions:
Could anyone provide an example when it's really necessary (with explanation of that) and when cast would change the result or performance dramatically. Let's assume we use one of number of date literals mysql defines (http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html). For sake of simplicity let it be of YYYY-MM-DD ('2013-07-26') format (with any date you like)
Could anyone clarify what "best results" mean? The result is either expected, or not - what is the "best" in this case?
PS: the target mysql version is the latest 5.5 available and newer.
PPS: to make things clear:
The question assumes we use datetime/date compatible columns, not varchars etc
The question is about expanding type, not about narrowing
Look at simple example (MySql 5.6):
drop table dattes;
create table dattes(
id int,
da_te date,
name varchar(200)
);
set #x = 0;
insert into dattes
select (#x:=#x+1),
'2013-5-1' + interval #x day,
t.column_name
from information_schema.columns t
;
and here is a query:
Set #start_date = cast( '2013-5-2' as date);
Set #start_datetime = cast( '2013-5-2 15:00' as datetime);
Set #end_date = cast( '2013-5-10' as date);
select (Select sum( id ) from dattes
where da_te between #start_date and #end_date) da_test1,
(Select sum( id ) from dattes
where da_te between #start_datetime and #end_date) da_test2,
(Select sum( id ) from dattes
where da_te between cast( #start_datetime as date)
and #end_date) da_test3
;
+ ------------- + ------------- + ------------- +
| da_test1 | da_test2 | da_test3 |
+ ------------- + ------------- + ------------- +
| 45 | 44 | 45 |
+ ------------- + ------------- + ------------- +
One would expect that in 2nd case MySql would implicitely convert #start_datetime to date (because the column da_te in the table is date) -> but MySql did the opposite, it widen other arguments to datetime. Because of this one record from the table was skipped ( '2013-5-2 00:00' < '2013-5-2 15:00').
This affects performance of course (maybe not dramatically, but a little), because MySql must convert all column values (or values of an index, if is any) from date to datetime.
I'm curious what the right way is to construct a query where the rows are pulled based on a timestamp that represents a specific month. Given that different months have different numbers of days, is there a way to generate a query that always gives you the rows where the timestamp contains the current month so that the results would only include the current month?
Do you mean something like this
SELECT * FROM tbl WHERE
MONTH(timesp) = MONTH(NOW()) AND
YEAR(timesp) = YEAR(NOW());
You can use the FROM_UNIXTIME() function:
SELECT *
FROM tableName
WHERE MONTH(FROM_UNIXTIME(timestampField))==6
Just use MONTH:
select *
from foo
where month_column = MONTH(getdate())
and year_column = YEAR(getdate())
Try this sql.
select *
from yourtable
where yourdatefield>=DATE_SUB(CURDATE(),INTERVAL 1 MONTH);
You're looking for something like this:
SELECT * FROM table where MONTH(date_row) = $month;
If you have an index on your date field, then this is efficient (T-SQL syntax, the idea applieas to any RDBMS though)
SELECT
*
FROM
tableName
WHERE
dateTimeField
BETWEEN
-- build the string 'YYYY-MM-01', cast back as a datetime
CAST(
CAST(YEAR(GETDATE()) AS varchar) + '-' + CAST(MONTH(GETDATE()) AS varchar) + '-01'
AS datetime
)
AND
-- add one month, subtract one day
DATEADD(mm, 1,
-- build the string 'YYYY-MM-01', cast back as a datetime
CAST(
CAST(YEAR(GETDATE()) AS varchar) + '-' + CAST(MONTH(GETDATE()) AS varchar) + '-01'
AS datetime
)
) - 1
Of course any other method to get two datetime values in the right range would work.
SQL Server has LEFT(CONVERT(varchar, GETDATE(), 120), 8) + '01' to convert a datetime to string, other Db servers have their own functions to do the same. Maybe you can calculate the two values in the calling application more easily - how you get them, is not the point.
The point is that BETWEEN can use an index, whereas the other solutions that work with WHERE MONTH(dateTimeField) = 6 will trigger a table scan, which is about the slowest operation you can do on a table.