MSSQL Date Format - sql

i want to get sql date format as follow
this is i tried code
select case when
left(datepart(day,getdate()),1)=4 then concat(datepart(day,getdate()),'th',' of ',DATENAME(month,GETDATE()),' ',datepart(year,getdate()))
end
this is output from my query 4th of August 2020

DECLARE #day int = datepart(day,getdate())
SELECT CONCAT(#day,
CASE WHEN #day=1 OR #day=21 OR #day=31 THEN 'st'
WHEN #day=2 OR #day=22 THEN 'nd'
WHEN #day=3 OR #day=23 THEN 'rd' ELSE 'th' END, ' of ',DATENAME(month,GETDATE()),' ',datepart(year,getdate()) )AS 'Date'
Would give you something like that.
Edit : if you make it as function, and pass it date as param you could use that pretty much anywhere. Will need to replace getdate() with parameter name then
CREATE FUNCTION [dbo].[fnc_GetDateString]
(
#date DATETIME
)
RETURNS nvarchar(100)
AS
BEGIN
--DECLARE #date DATETIME = '2020-08-31'
DECLARE #day int = datepart(day,#date)
DECLARE #DateString nvarchar(100)
SET #DateString = CONCAT(#day,
CASE WHEN #day=1 OR #day=21 OR #day=31 THEN 'st'
WHEN #day=2 OR #day=22 THEN 'nd'
WHEN #day=3 OR #day=23 THEN 'rd' ELSE 'th' END, ' of ',DATENAME(month,#date),' ',datepart(year,#date) )
RETURN #DateString
END

Related

Dates returned as columns in SQL Select

My user will submit a FromDate and a ToDate. What I want to happen is to select the dates that fall in between these dates, which I have accomplished with the script below. The dates will by dynamic.
DECLARE #fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE #toDateParam DATETIME = '2022-01-29 00:00:00.000'
;WITH fnDateNow(DayOfDate) AS
(
SELECT #fromDateParam AS TransactionDate
UNION ALL
SELECT DayOfDate + 1
FROM fnDateNow
WHERE DayOfDate < #toDateParam
)
SELECT fnDateNow.DayOfDate AS TransactionDate
FROM fnDateNow
This returns that dates as rows. What I am looking for is a way to make these dates return as the columns for a different script.
This table is called DailyTransactionHeader and it has a column [TransactionDate] and another one called [Amount].
There is the probability that their is not a DailyTransactionHeader with the specified Date for this I am looking to return 0.
So I am trying to have the data look like this (I formatted the date) There would be more than one row, but I just wanted to show an example of what I am trying to accomplish.
I appreciate any help,
Thanks
You can do it using dynamic sql. For example:
CREATE PROCEDURE [GET_DATE_TABLE]
(
#FROMDATE DATETIME,
#TODATE DATETIME
)
AS
DECLARE #PDATE DATETIME
DECLARE #SQL VARCHAR(MAX)
DECLARE #SEP VARCHAR(10)
SET #PDATE = #FROMDATE
SET #SQL = 'SELECT '
SET #SEP = ''
WHILE #PDATE < #TODATE
BEGIN
SET #SQL = #SQL + #SEP + 'NULL as [' + CONVERT(VARCHAR, CONVERT(DATE, #PDATE)) + ']'
SET #PDATE = #PDATE + 1
SET #SEP = ', '
END;
EXEC(#SQL)
Test Example:
DECLARE #fromDateParam DATETIME = '2022-01-24 00:00:00.000'
DECLARE #toDateParam DATETIME = '2022-01-29 00:00:00.000'
exec dbo.GET_DATE_TABLE #fromDateParam, #toDateParam

SQL Select statement, change Format mmddyy to dd-mon-yyyy with convert

I want to select field opendate mmddyy data type decimal(6,0) to dd-mon-yyyy. How do I modify this statement?
select convert(varchar(10),M.opendate, 106)
FROM All.Customer M
The above results in the following error:
[SQL0204] CONVERT in *LIBL type *N not found
You can try this:
DECLARE #InputDate VARCHAR(8)
SET #InputDate = '073019'
DECLARE #InputYear VARCHAR(4)
DECLARE #InputMonth VARCHAR(2)
DECLARE #InputDay VARCHAR(2)
SET #InputYear = '20' + SUBSTRING(#InputDate, 5, 2)
SET #InputMonth = LEFT(#InputDate, 2)
SET #InputDay = SUBSTRING(#InputDate, 3, 2)
DECLARE #OutputDate DATE
SET #OutputDate = #InputYear +'-'+ #InputMonth +'-'+ #InputDay
SELECT CONVERT(VARCHAR(15), #OutputDate, 106)
Still you should know how to define the first 2 digits of the year. I have used '20' as default.

How to define if a string is date or datetime?

I have incoming string, for instance 12.10.03 00:00:00.0000000. How to define if there is time in this string or just date?
Note that, date and time can have different formats. For example:
date can be January 03, 2012
time can be 1:1
If this doesn't return zero there is time:
SELECT DATEDIFF(SECOND,#VariableOrColumn,CAST(#VariableOrColumn AS DATE))
Add more precision for DATETIME2(7) by adding nano seconds if needed.
Use the LIKE operator;
if (#MyString like '%[0-9][0-9]:[0-9][0-9]:[0-9][0-9]%') ...
You can write as:
SELECT CASE WHEN PATINDEX( '%:%','12.10.03 00:00:00.0000000')> 0 THEN 'datetime'
ELSE 'Date' END AS Result
and to validate a date you can use ISDATE function.
You can take like this:
SELECT x = SUBSTRING('12.10.03 00:00:00.0000000', 1, 8);
Edit code for different formats;
SUBSTRING('12.10.03 00:00:00.0000000', 1,CHARINDEX(' ','12.10.03 00:00:00.0000000'));
First cast your string as datetime to put it in a proper format then just cast the resulting datetime as time and compare it with midnight as time and viola:
Select Case when Cast(Cast(#yourstring as datetime) as Time) = Cast('00:00:00.0000000' as time) then Cast(#yourstring as date) else Cast(#yourstring as datetime) end
if(#x='12.10.03').it is valid datetime and time is 00:00:00
if(#x='12.10.03 00:00:00.0000000').it is valid datetime and time is again 00:00:00
So what do you mean by saying if it contain time.
you can test this script thoroughly with different input .I tested and its running fine .
BEGIN TRY
declare #x varchar(32) = '12.10.03 00:00:00.0000000'
-- or '12.10.03' or '00:00:00.0000000' or '0000000' or 'fgdfgg'
Declare #outputdt datetime2(7)
Declare #hr int
Declare #minute int
Declare #sec int
set #outputdt=#x
--select #outputdt
if isdate(LEFT(#x, 21))=1
BEGIN
select LEFT(#x, 21)
select #hr=DATEPART(hour,#outputdt)
,#minute=DATEPART(minute,#outputdt)
,#sec=DATEPART(minute,#outputdt)
END
else
BEGIN
select #hr=DATEPART(hour,#outputdt)
,#minute=DATEPART(minute,#outputdt)
,#sec=DATEPART(minute,#outputdt)
select 'Not valid1'
END
END TRY
BEGIN CATCH
select 'not valid'
END CATCH
select #hr,#minute
if(#hr>0)
select 'Todo'
After some r&d , I do this and I think this will help you.
You are not mention Sql version, so this sample will work SQLSERVER2008 and above
For more info :-
http://blog.sqlauthority.com/2012/09/12/sql-server-get-date-and-time-from-current-datetime-sql-in-sixty-seconds-025-video/
declare #s nvarchar(200) = '12.10.03' -- 00:00:00.0000000'
--select CONVERT(time, #s)
Select
case
when isdate(#s ) = 1
then
case
when CONVERT(time, #s) = '00:00:00.0000000'
then 'no time'
else 'it has time'
end
else
'no time'
end
as dateHaveTimeOrNOT
set #s = '12.10.03 01:20:00'
Select cast (#s as date) , isdate(#s ),CONVERT(time, #s),
case
when isdate(#s ) = 1
then
case
when CONVERT(time, #s) = '00:00:00.0000000'
then 'no time'
else 'it has time'
end
else
'no time'
end
as dateHaveTimeOrNOT

why doesn't date show am or pm

Why am I not getting time with am or pm
DECLARE #inputDate varchar(25)
SELECT #inputDate = '3/13/2012 13:00'
-- Declare the return variable here
DECLARE #Result DATETIME
DECLARE #toReturn NVARCHAR(25)
-- Add the T-SQL statements to compute the return value here
SET #inputDate = REPLACE(#inputDate, '24:00', '00:00')
SET #Result = null
SET #toReturn = null
IF (ISDATE(#inputDate)=1)
BEGIN
DECLARE #utcOffset int
SET #utcOffset = -(DATEDIFF(HH, GETUTCDATE(), GETDATE()))
SET #Result = DATEADD(HH, #utcOffset, #inputDate)
SET #toReturn = CONVERT(NVARCHAR, #Result, 101)
END
-- Return the result of the function
SELECT #toReturn
Returns only date portion?
You will need to change CONVERT(NVARCHAR, #Result, 101) to something else. 101 returns a mm/dd/yyyy format. See here for more details: http://msdn.microsoft.com/en-us/library/ms187928.aspx
You are using 101 in your last convert statement and that is date only.
Have a look here for other options. CAST and CONVERT (Transact-SQL)
Try another date format instead of 101 in CONVERT operator.
Because your final conversion uses a format that only includes dates - no time component.
Try the following, instead:
SET #toReturn = CONVERT(NVARCHAR, #Result, 121)

Return Static date using SQL Function

I have a situation where i need to return a date.Here for this function i will be supplying month number and i need to return result like "3/13/2012".
declare #date varchar(20)
select #date=datepart(month,getdate())+'/13/'+datepart(year,getdate())
return #date(#date)
This should do it for ya.
CREATE FUNCTION dbo.fnStaticDate(#month varchar(2))
RETURNS DATETIME
AS
BEGIN
DECLARE #year VARCHAR(4)
SET #year = DATEPART(year, GETDATE())
RETURN CONVERT(DATETIME, #year + '-' + #month + '-' + '13')
END
Here is the working solution which i have used for one of my project.
created a store procedure with input parameter of month
declare #mon varchar(2)
set #mon = '3'
select CONVERT(varchar, #mon + '/13/' + convert(varchar, datepart(year, getdate())), 111 )
execute the above lines in SQL server you will get the result.
test by changing the #mon value in set statement.
Hope it helps you.
conversion error it gives
declare #date varchar(20)
select #date=convert(varchar(2),datepart(month,getdate()))+'/13/'+convert(varchar(4),datepart(year,ge tdate()))
print (#date)