dateformat not as expected - sql

I have the following function below.
It returns a date like Feb 29 2012 10:00PM. Is there a way to make it return the format as 2/29/2012 10:00PM
CREATE FUNCTION scrubDateString
(
-- Add the parameters for the function here
#inputDate varchar(150)
)
RETURNS DATETIME
AS
BEGIN
-- Declare the return variable here
DECLARE #Result DATETIME
-- Add the T-SQL statements to compute the return value here
DECLARE #tmpDate datetime
SET #Result = null
IF (ISDATE(#inputDate)=1)
BEGIN
SET #Result = DATEADD(HH, 5, #inputDate)
END
-- Return the result of the function
RETURN #Result
END

The function itself is returning a Date and time, "Feb 29 2012 10:00PM" and "2/29/2012 10:00AM" are merely string representations of that date (I am assuming that the AM and PM switch are not relevant to the question and are just a mistake). IF you want to format the date as a particular string look at the CONVERT function. e.g:
DECLARE #Date DATETIME
SET #Date = scrubDateString(#YourString)
SELECT CONVERT(VARCHAR, #Date, 101) + ' ' + RIGHT(CONVERT(VARCHAR, #Date, 0), 7) [Date]
Although I'd strongly advise leaving your date as a date, and doing any formatting on the application side if at all possible. If I have assumed wrong about the AM PM switch you could alter the code above to the following:
DECLARE #Date DATETIME
SET #Date = scrubDateString(#YourString)
IF (DATEPART(HOUR, #Date) > 12)
BEGIN
SET #Date = DATEADD(HOUR, -12, #Date)
END
SELECT CONVERT(VARCHAR, #Date, 101) + ' ' + RIGHT(CONVERT(VARCHAR, #Date, 0), 7) [Date]

If you want to format a DateTime you will need to return it as VARCHAR instead of as a date. If you declare a FUNCTION to return DateTime then it will always return a DateTime formatted in the standard SQL way.
You can return it as a string by using the sql CONVERT function:
RETURN CONVERT(varchar(500), #Result, 101)
A list of formats can be found on msdn. If you want a different format then you need to do something like what's discussed in this question

just change\add this:
SET #Result = DATEADD(HH, 5, #inputDate)
SET #Result = CONVERT(VARCHAR(10), #Result , 101) + ' ' + RIGHT(CONVERT(VARCHAR, GETDATE(), 100), 7)
you can make it on one line, of course, just did on 2 for clarity
forgot to add that you need to change the return variable to varchar, instead of datetime.
If you cant do that, maybe you can add the convert to the places that are calling the function (which would be worst, for sure)

Related

How to pass the Datetime value as parameter to a stored function?

I created a function in SQL SERVER that takes in parameter a datetime value, and when I tried to execute it, I didn't know how to pass a Datetime value as parameter to this function, I got this error : Failed to convert date and / or time from a string.
this is the code of my function :
CREATE FUNCTION [dbo].[nb_pieces_produites] (#dateInsertion datetime)
returns decimal(4,0)
AS
BEGIN
DECLARE #year decimal(4,0), #month decimal(2,0), #day decimal(2,0) ,#hour
decimal(2,0), #nbPiecesProduites decimal(4,0)
set #year = (select DATEPART(yyyy, #dateInsertion))
set #month = (select DATEPART(mm, #dateInsertion))
set #day = (select DATEPART(dd, #dateInsertion))
set #hour = (select DATEPART(hh, #dateInsertion))
set #nbPiecesProduites = (SELECT COUNT(DISTINCT Num_Serie) FROM [dbo].
[dbo_Test] WHERE #dateInsertion BETWEEN '#year-#month-#day #hour:00:00' AND
'#year-#month-#day #hour:59:59')
return #nbPiecesProduites
END
and this is my query :
select [dbo].[nb_pieces_produites]('2017-06-19 11:38:52')
Can anyone help me please ?
Don't spend lots of time fiddling around with strings - try to keep your data as datetime data throughout.
To round a datetime down to the previous hour boundary, use a DATEADD/DATEDIFF pair:
CREATE FUNCTION [dbo].[nb_pieces_produites] (#dateInsertion datetime)
returns decimal(4,0)
AS
BEGIN
set #nbPiecesProduites = (SELECT COUNT(DISTINCT Num_Serie) FROM [dbo].
[dbo_Test] WHERE
date_column_from_table >= DATEADD(hour,DATEDIFF(hour,0,#dateInsertion),0)
AND
date_column_from_table < DATEADD(hour,DATEDIFF(hour,0,#dateInsertion)+1,0)
)
return #nbPiecesProduites
END
And, just to be safe, call it like this:
select [dbo].[nb_pieces_produites]('2017-06-19T11:38:52')
(Occasionally, under some settings, SQL Server will interpret nnnn-nn-nn as yyyy-dd-mm rather than yyyy-mm-dd, if it's followed by a space and then a time, rather than using T as the separator)
it's error because your function expect dateTime value, but when you called it you passing string not dateTime
change your query into :
select [dbo].[nb_pieces_produites](getDate())
CREATE FUNCTION [dbo].[nb_pieces_produites] (#dateInsertion datetime)
RETURNS decimal(4,0)
AS
BEGIN
RETURN
(
SELECT COUNT(DISTINCT Num_Serie)
FROM dbo.dbo_Test
WHERE
-- Use the date part to compare
CONVERT(date, [datetimecolumn]) = CONVERT(date, #dateInsertion)
-- Then compare with hour
AND DATEPART(HOUR, [datetimecolumn]) = DATEPART(HOUR, #dateInsertion)
)
END

SQL Date/Time Format

How to convert date/time from 20150323153528 to 2015-03-23 15:35:28.000. I need this to filter based on the getdate(). Thanks in advance.
Select * from table
Where 20150323153528 > GETDATE() - 7
Statement to convert date to your requirement
DECLARE #Date varchar(20) = '20150323153528'
Select * from table Where
CONVERT(DATETIME, CONVERT(CHAR(8), #Date), 121) + ' ' + stuff(stuff(right('000000' + cast(#Date as varchar),6),5,0,':'),3,0,':') as DATETIME > GETDATE() - 7
In MS SQL you could use
DECLARE #Date varchar(20) = '20150323153528'
Select * from table Where CAST(convert(varchar,#Date) as datetime) > GETDATE() - 7
Please read this page.
SELECT convert(varchar, getdate(), 120) — yyyy-mm-dd hh:mm:ss(24h)
Note: I assume this is a Microsoft SQL Server environment using T-SQL:
The formatting of date / datetime values is not a concern of T-SQL. You should do that in your presentation-layer (i.e. your frontend code).
If you have date/time values represented as integers of the form 20150323153528 then you cannot use them in T-SQL. You need to convert them to strings (preferably in ISO-8601 format) for SQL Server to successfully internally convert them to datetime (or datetimeoffset) values which can then be compared with other datetime values.
I suggest performing the conversion in your application code before you send it to SQL, as a datetime-typed parameter value, like so:
Int32 weirdDateValue = 20150323153528;
String s = weirdDateValue.ToString( CultureInfo.InvariantCulture );
String dtValueAsIso8601 = String.Format("{0}-{1}-{2} {3}:{4}:{5}.{6}",
s.Substring(0, 4), s.Substring(4, 2), s.Substring(6, 2),
s.Substring(8, 2), s.Substring(10, 2), s.Substring(12, 2), s.Substring(14)
);
DateTime dtValue = DateTime.ParseExact( dtValueAsIso8601, "yyyy-MM-dd HH:mm:ss.fff" );
cmd.Parameters.Add("#dtValue", SqlDbType.DateTime).Value = dtValue;
In T-SQL the process is pretty much the same, except using MID - note that MID uses 1-based character indexes instead of 0-based:
DECLARE #input int = 20150323153528
DECLARE #s varchar( 14 ) = CONVERT( #input, nvarchar(14) )
DECLARE #dtStr varchar( 24 ) = MID( #s, 1, 2 ) + '-' + MID( #s, 3, 2 ) + '-' + MID( #s, 5, 2 ) + ' ' + -- etc...
DECLARE #dt datetime = CONVERT( #dtStr, datetime )
SELECT
*
FROM
[table]
WHERE
#dt > GETDATE() - 7
If the integer values are stored in an actual column instead of a parameter you'll need to convert the logic into a scalar UDF which performs the conversion. I strongly suggest you change the table's design to add a strongly-typed datetime column and permanently store the value there, and then drop the datetime-as-int column:
CREATE FUNCTION ConvertIntDateIntoDateTime(#dateAsInt int) RETURNS datetime AS
BEGIN
-- same code as above minus the SELECT statement
RETURN #dt
END
Used in an inner subquery to allow the data to be accessed in WHERE statements, like so:
SELECT
*
FROM
(
SELECT
*,
dbo.ConvertIntDateIntoDateTime( someDateColumn ) AS someDateColumn2
FROM
[table]
) AS FixedTable
WHERE
FixedTable.someDateColumn2 > GETDATE() - 7

How to add 1 day to current date and have result in format yyyymmdd in SQL Server?

I need to add 1 day to the current date and have the output in the format yyyymmdd.
The code needs to be written on a stored procedure on the sql server.
currently my code is as follows:
DECLARE #dat DATE
select #dat = dateadd(DD, 1, getdate())
SELECT #dat =LEFT(CONVERT(VARCHAR(8), #dat, 112),10)
However, it seems like im doing something wrong as my output on the sql table is in the format yyyy-mm-dd. I need to get rid of the hyphens.
any suggestions guys? thanks in advance.
The issue is that you are assigning it back to a date object. You need to assign it to a varchar.
I did the following in SQL Server 2005:
DECLARE #dat DATETIME
DECLARE #string varchar(8)
SET #dat = GetUtcDate()
select #dat = dateadd(DD, 1, getdate())
SELECT #string =CONVERT(VARCHAR(8), #dat, 112)
PRINT #string
Change the declaration of #dat to a STRING
Try this one -
DECLARE #date VARCHAR(8)
SELECT #date = CONVERT(VARCHAR(8), DATEADD(DAY, 1, GETDATE()), 112)
SELECT #date
select #dat = dateadd(DD, 1, getdate())
DECLARE #datCus varchar(8)
select #datCus=LEFT(CONVERT(VARCHAR(8), #dat, 112),10)
The problem was that i assigned #dat to the insert statements values. However having a varchar variable to handle the converting part solved the problem (in this case #datCus).

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)