Homework - Getting DateTime in custom format in MS SQL - sql-server

How do I select a value from a DateTime column in the DD-MM-YYYY HH:MI:SS (HH is 24-hour) format?
P.S.: The return vale of the SELECT query can be any datatype.

Seeing as this is homework, just some tips:
You need to read up on the Convert Sql function. Then, you need to realise that your requirement is a mix of two different formats (one for the date; hint - Italian) and one for the time part. Simply Convert your date into the two formats and concatentate them with a space in between
Your code will end up looking like the following:
select
CONVERT(VARCHAR(10), your_date, date_format ) + ' ' + CONVERT(VARCHAR(10), your_date,time_format )
from ...

Here is how to do it
DECLARE #dt DATETIME
SET #dt = GETDATE()
PRINT CONVERT(varchar, #dt, 103) + ' ' + CONVERT(varchar, #dt, 108)
In a select statement it would look like:
SELECT CONVERT(varchar, yourDateField, 103) + ' ' +
CONVERT(varchar, yourDateField, 108) as YourFieldName, ...
FROM ...
WHERE ...

Related

Print a sentence saying the day of the year using SQL Server

I am trying to write this using SQL SERVER:
"Hi! Today is ... This is the day number... of the year. New year's eve is in ... days".
My code runs with no problem but I can't print as well. What am I doing wrong? I haven't finished the whole phrase because I need to fix the problem before I get to the last part.
DECLARE
#currentDate DateTime
SET #currentDate = GETDATE();
DECLARE #dayofyear datetime
SET #dayofyear=DATEDIFF(day,STR(YEAR(#dayofyear),4)+'0101',#dayofyear)+1
-- SELECT Numbertoday = DATEDIFF(day,STR(YEAR(#dayofyear),4)+'0101',#dayofyear)+1
print('Hi! Today is '+ CONVERT(VARCHAR(10), #currentDate , 111) + '. ' + 'This is the day number '+ ' ' + CONVERT (VARCHAR(10), #dayofyear) + of the year.')
Another way to do is:
declare #today varchar(11) = convert(varchar(11), getdate(), 1);
declare #dayOfTheYear int = datepart(DAYOFYEAR, getdate());
declare #untilNewYearsEve int = datepart(dayofyear, datefromparts(year(getdate()), 12, 31)) - #dayOfTheYear
-- if you use print, you should see the result under the 'messages' tab not in the 'results' tab in SSMS
print 'Hi! Today is '+ #today + '. ' + 'This is the day number '+ cast( #dayOfTheYear as varchar(3)) + '. New year''s eve is in '+
cast (#untilNewYearsEve as varchar(3)) + ' days.'
This should work perfectly fine.
while seeting the day of year you need to put #current date so it will work because you are trying to get a day from a #currentdate
DECLARE
#currentDate DateTime
SET #currentDate = GETDATE();
DECLARE #dayofyear datetime
SET #dayofyear=DATEDIFF(day,STR(YEAR(#currentDate),4)+'0101',#currentDate)+1
print('Hi! Today is '+ CONVERT(VARCHAR(10), #currentDate , 111) + '. ' + 'This is the day number '+ ' ' + CONVERT (VARCHAR(10), #dayofyear) + 'of the year.')
Just for fun, you can use concat()
Example
Print concat('Hi! Today is '
,format(GetDate(),'dddd, MMM d, yyyy.')
,' This is the day number '
,DateDiff(DAY,datename(YEAR,getdate())+'0101',getdate()) + 1
,' of the year.'
)
Results
Hi! Today is Thursday, Jul 4, 2019. This is the day number 185 of the year.
You can simplify things a bit using DAYOFYEAR parameter in the DATEPART function if using SQL 2008 and above. And you don't really need to declare a variable for the date.
Sample Code:
print('Hi! Today is '+ convert(varchar(10), getdate() , 111) + '. ' + 'This is the day number' + ' ' + convert(varchar, datepart(dayofyear, getdate()))) + ' of the year.'
Results:
Hi! Today is 2019/07/05. This is the day number 186 of the year.

How to convert/cast column data type in concatenated SQL query string

i have the following variables defined in my stored procedure
#StartDate DateTime,
#EndDate DateTime,
I'm setting the sql to be executed dynamically, so when constructing the query where clause i have the below line.
SET #sql = #sql + ' AND (convert(datetime, R.ReportDate, 121) >= ' + #StartDate + 'AND convert(datetime, R.ReportDate, 121) <=' + #EndDate +')'
When i execute the stored procedure, the line above throws the error below
Conversion failed when converting datetime from character string.
If i change the variable datatype to NVARCHAR(MAX), the procedure executes successfully but then returns no rows because the date comparison/matching fails.
ReportDate column is of datatype datetime and has data in this format 2014-06-01 00:00:00.000
As you can see i have tried converting the column when constructing my query but that isn't working.
The problem is not with ReportDate, but when you are trying to concatenate your DateTime parameters with your nvarchar sql statement. The problem can be reproduced fairly simply with:
DECLARE #SQL NVARCHAR(MAX) = 'Some text' + GETDATE();
The wrong way to fix this is to convert the datetime parameter to a string so that it can be concatenated with a string, e.g.
SET #sql = #sql + ' AND r.ReportDate >= CONVERT(DATETIME, '''
+ CONVERT(VARCHAR(10), #StartDate, 112)
+ ''', 112) AND r.ReportDate <= CONVERT(DATETIME, ''' +
+ CONVERT(VARCHAR(10), #EndDate, 112)
+ ''', 112)';
N.B. I am including this for completeness of the answer, and in no way endorse this approach
The correct way to fix this is to use sp_executesql and pass properly typed parameters this way, this will avoid conversion issues. e.g.
SET #sql = #sql + 'AND r.ReportDate >= #StartDateParam AND r.ReportDate <= #EndDateParam';
EXECUTE sp_executesql
#sql,
N'#StartDateParam DATETIME, #EndDateParam DATETIME',
#StartDateParam = #StartDate,
#EndDateParam = #EndDate

SQL Server 2005 date format with day name Monday, May 5th 2014 (without time)

What format string will do this?
Monday, May 5th 2014
Is there a simple way to do it?
I've looked at various combinations of CONVERT.
FORMAT only works in 2008
Convert has a "secret option". Convert(Varchar(20), mydate, 103). See Convert formats for a lot of other options.
See: http://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
Not exactly what you are looking for but somewhat close...
DECLARE #Date DATETIME;
SET #Date = GETDATE();
SELECT DATENAME(DW,#Date) + ', '
+ DATENAME(MONTH, #Date)
+ RIGHT(CONVERT(VARCHAR(12), #Date, 107), 9)
RESULT: Monday, May 05, 2014
Another Option:
SELECT DATENAME(DW,#Date) + ', '
+DATENAME(MONTH, #Date) + ' '
+ CAST(DAY(#Date) AS VARCHAR(2))
+ ' ' + CAST(YEAR(#Date) AS NVARCHAR(4))
RESULT: Monday, May 5 2014

Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server

How to convert given date format to MM/dd/yyyy HH:mm:ss
I tried this one below but not achieved. Can anyone help me?
SELECT CONVERT(VARCHAR(20), GETDATE(), 120)
Supported by SQL Server 2005 and later versions
SELECT CONVERT(VARCHAR(10), GETDATE(), 101)
+ ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)
* See Microsoft's documentation to understand what the 101 and 108 style codes above mean.
Supported by SQL Server 2012 and later versions
SELECT FORMAT(GETDATE() , 'MM/dd/yyyy HH:mm:ss')
Result
Both of the above methods will return:
10/16/2013 17:00:20
Try below:
SELECT CONVERT(VARCHAR(20), GETDATE(), 101)
use
select convert(varchar(10),GETDATE(), 103) +
' '+
right(convert(varchar(32),GETDATE(),108),8) AS Date_Time
It will Produce:
Date_Time 30/03/2015 11:51:40
Declare #month as char(2)
Declare #date as char(2)
Declare #year as char(4)
declare #time as char(8)
declare #customdate as varchar(20)
set #month = MONTH(GetDate());
set #date = Day(GetDate());
set #year = year(GetDate());
set #customdate= #month+'/'+#date+'/'+#year+' '+ CONVERT(varchar(8), GETDATE(),108);
print(#customdate)

Converting DateTime to nvarchar, just month and year

How to convert the datetime value to nvarchar and want to format it "Month, Year" e-g October 1st 2009 value should get converted to "October, 2009"
use this:
select CONVERT(nvarchar(50), DATENAME(m, getdate())
+ ', '
+ DATENAME(yyyy, getdate())
)
OUTPUT:
--------------------------------------------------
October, 2009
(1 row(s) affected)
Try this
DECLARE #DateTime DATETIME
SET #DateTime = '01 Oct 2009'
SELECT #DateTime
SELECT DATENAME(mm, #DateTime) + ', ' + CAST(DATEPART(yy, #DateTime) AS VARCHAR(4))
One way would be to use datename to extract the pieces you needed in name format, so:
select Convert(nvarchar,datename(m,getdate())) + N', ' + Convert(nvarchar,datename
(yy,getdate()))
And replace getdate() with your date variable / field.
The DateName function will provide the formatting you require:
DATENAME(m, date) + ', ' + DATENAME(yyyy, date)
Converting to nvarchar of a specific size can be done through the cast function:
CAST(value AS nvarchar[30])
Try the following query:
Select case Convert(int, day(getdate())) when 1 then '1st' when 2 then '2nd'
when 3 then '3rd' else Convert(varchar, day(getdate()))+'th' end +' '+ Convert(varchar, Datename(m,getdate()))+' ' +Convert(varchar, Datename(yy,getdate())) as Date
You can replace getdate() with any other date.
Please check if it helps.

Resources