How to concatenate Date and DateName together - sql-server-2008

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]

Related

MYSQL Fetch Date and Time Stored as String and ORDER BY

I have a specific reason for storing Date and Time in DataBase Table as String in below format
DateFmt = "dd-MM-yyyy";
TimeFmt = "hh:mm a";
Now while fetching I want to sort by converting the string to Date and Time and sort to display in TableView, so the row with newer ones come on top.
This wil work if we store as date and time,
ORDER BY `DATE` DESC, `TIME` DESC
How do we convert from String and use order by
Use str_to_date():
order by str_to_date(date, '%d-%m-%Y')
I should add: I can think of no good reason for storing a date in that format in the database. You should be using the built-in date/time types. They exist for a reason.
If you do have to store a date as a string (which I have to do occasionally), you should use YYYY-MM-DD format. This is ISO standard, converts readily to a date, and sorts correctly.
I came with the solution like this :
SQL :
SELECT * FROM NamTbl
ORDER BY STR_TO_DATE(CONCAT(DateCol,' ',TimeCol), '%d-%m-%Y %h:%i') DESC
SQLite :
"SELECT * FROM " + NamTblVar +
" ORDER BY STRFTIME('%d-%m-%Y %h:%i'," + DateKolVar + "|| ' ' ||" + TimeKolVar + ") DESC;";

Convert string yyyymmddhhmmss into hh:mm:ss format in SQL

With the string DATETIME yyyymmddhhmmss like 20160125173013, I would like to convert this string into hh:mm:ss (17:30:13) as a new column called "Time" in a table with sql update statement. However I am only able to convert it into 17:30 using the stuff function.
Is there any possible solution to convert?
In my statement
UPDATE db
SET Time =convert(time, stuff(substring(DATETIME,9,6),3,2,':'))
FROM db
WHERE Time IS NULL
Real Output=17:13:00.0000000
But my expected output is 17:13:00
Thanks a lot!
Here is the miracle for mysql:
SELECT time(str_to_date('20160125173013', '%Y%m%d%H%i%s'));
Do you have an actual DATETIME field? If so you can use DATE_FORMAT():
UPDATE mytable SET my_time=DATE_FORMAT(my_date, '%H:%i:%s')
If you don't have a native DATETIME field I hope you can convert it to one, as irregular, quirky formats cause trouble and introduce a lot of overhead when parsing to convert. STR_TO_DATE() can do the opposite of DATE_FORMAT() and convert from arbitrary strings to native DATE or DATETIME values.
Don't confuse STORAGE with PRESENTATION
Declare #YourTable table (DateTime varchar(25),Time time)
Insert Into #YourTable values
('20160125173013',null)
Update #YourTable
Set Time = stuff(left(right(DateTime,6),4),3,0,':')
Select *
,FormatedTime = Format(cast(Time as datetime),'HH:mm')
From #YourTable
Returns
DateTime Time FormatedTime
20160125173013 17:30:00.0000000 17:30
Based on the use of the STUFF function I believe this is Microsoft SQL Server, and not MySql.
Therefor, you can do something like this:
UPDATE db
SET [Time] = CAST(SUBSTRING([DATETIME], 9, 2) +':'+
SUBSTRING([DATETIME], 11, 2) +':'+
RIGHT([DATETIME], 2) As Time)
WHERE [Time] IS NULL
Your string is no format, SQL Server will cast implicitly
DECLARE #YourDateTimeString VARCHAR(100)='20160125173013';
The following query will cut the first 8 digits and cast them to DATE, which works implicitly (unseparated format). The time is cut from the right side, then the two :-signs are stuffed into the right places:
SELECT CAST(LEFT(#YourDateTimeString,8) AS DATE)
,CAST(STUFF(STUFF(RIGHT(#YourDateTimeString,6),5,0,':'),3,0,':') AS TIME);
The result
2016-01-25 17:30:13.0000000
If you need this as string without the trailing .0000000 (which is a pure output format question and should be done in your presentation layer!) you can just use LEFT(). The input of this function is string (again implicitly casted), the output is a text which looks like a time.
SELECT CAST(LEFT(#YourDateTimeString,8) AS DATE)
,LEFT(CAST(STUFF(STUFF(RIGHT(#YourDateTimeString,6),5,0,':'),3,0,':') AS TIME),8);
The result
2016-01-25 17:30:13
If you ar eusing SQL server then use Convert function
Declare #VarCharDate varchar(max)
Declare #VarCharDate1 varchar(max)
--Declare
set #VarCharDate = '20160125173013' --- YYYYMMDDHHMMSS
--Convert
set #VarCharDate1 =(select SUBSTRING(#VarCharDate,0,5) + '/' +
SUBSTRING(#VarCharDate,5,2) + '/' + SUBSTRING(#VarCharDate,7,2)
+ ' ' + SUBSTRING(#VarCharDate,9,2)
+':'+SUBSTRING(#VarCharDate,11,2) +':' + RIGHT(#VarCharDate,2))
select #VarCharDate1
select Convert(varchar(8),convert(datetime, #VarCharDate1, 120),114)

Cast different parts of a varchar into a date time, SQL

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

SSIS derived column expression for date difference

I have an column in my source table as [Valyyyymmdd] [nvarchar](24) NULL:
Valyyyymmdd
=================
20130503
20120403
00000000
20110523
20100715
I want to get the difference with getdate(), so I used the below query in my source
DATEDIFF(DAY, IIF( [Valyyyymmdd] = '00000000', CONVERT(VARCHAR(8), GETDATE(), 112), [Valyyyymmdd]) , getdate()) as SalesStageAging
but I need to get the Valyyyymmdd and do ssis derived column to get the difference in date resulting in int value.
Kindly provide me the expression which has to be written in derived column expression
Try this:
DATEDIFF("d",[Valyyyymmdd] == "00000000" ? GETDATE() : (DT_DBDATE)(SUBSTRING([Valyyyymmdd],1,4) + "-" + SUBSTRING([Valyyyymmdd],5,2) + "-" + SUBSTRING([Valyyyymmdd],7,2)),GETDATE())
Assuming [Valyyyymmdd] is a string in the format "yyyyMMdd", we split it into the year, month and date parts, insert hyphens between parts to format it as "yyyy-MM-dd" and then cast it as a date i.e. datatype DT_DBDATE. Finally, we use the conditional operator to check if value equals "00000000", and compare either current date, or the date parsed from input with current date to return the result.

How does one construct a query that only returns this months rows, based on Timestamp?

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.