Convert Datetime in Stored Procedure - sql-server

I have Stored Procedure on SQL to get the time the database last updated. When O run the Query by itself, I get Month dd yyyy hh:mm AM/PM.
But when O execute stored procedure, I get yyyy-MM-dd hh:mm:ss
I need the Month dd yyyy hh:mm AM/Pm ( Apr 1 2022 7:30AM) format.
What Am I doing wrong in converting the datetime.
ALTER PROCEDURE [dbo].[spGetDBLastUpdatedTime]
-- Add the parameters for the stored procedure here
#LastUpdatedTime Datetime OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SET #LastUpdatedTime =(SELECT
convert(Varchar(MAX),last_user_update,100) as LastUpdatedTime
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'Emp')
AND OBJECT_ID=OBJECT_ID('tblEmployee'))
RETURN;
END

Real Datetime values DO NOT HAVE A STRING FORMAT AT ALL. What you see is a convenience shown you by the tool or environment where you ran the query. The actual value is a binary format. It's not really human-readable at all, but rather is more efficient for storage, transport, indexing, and operations like comparing or adding arbitrary days, months, milliseconds, etc.
If you need a specific format, still return a raw (unformatted) DateTime value from your database query, and then use the string conversion tools on whatever platform or reporting tool you're working with to get the desired format there, in the presentation level where it belongs.

Related

What is the default date style used by an instance of SQL Server when converting from varchar to datetime?

I've run this SQL query on two different servers:
declare #test as datetime='2020-05-06 00:00:00'
select Convert (nvarchar,#test)
The results were different on the two servers:
May 6 2020 12:00AM
Jun 5 2020 12:00AM
I know the reason behind this, when SQL Server is reading the string that I passed 2020-05-06 00:00:00 and converting it to DateTime in the declare statement, it's using the default date style.
Am I able to configure this default style, or in other words, how is default date style chosen in SQL Server when converting the varchar to datetime? Is it from the windows regional settings or some other configurations inside SQL Server?
It uses a style based on the language. Basically, for the date above, if you're American then the date will be read as yyyy-MM-dd hh:mm:ss, however, if use over languages, then it's be (stupidly) read as yyyy-dd-MM hh:mm:ss.
If you are using strings for dates (like your literal here) then aim to use an unambiguous format. In SQL Server, regardless of data type and language, those are yyyy-MM-ddThh:mm:ss.nnnnnnn and yyyyMMdd.
If you're convert to an (n)varchar, always use a style code (and a length for your varchar) for consistent results.
So, for your value, you can run the below to find out what the default conversion value would be for all the languages on your instance:
DECLARE Languages CURSOR FOR
SELECT alias
FROM sys.syslanguages;
DECLARE #Alias sysname,
#SQL nvarchar(MAX);
CREATE TABLE #ConvertedDates (Alias sysname, dt datetime, converted nvarchar(25));
DECLARE #dt datetime = '2020-05-06T00:00:00'
OPEN Languages
FETCH NEXT FROM Languages
INTO #Alias;
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQL = N'SET LANGUAGE ' + QUOTENAME(#Alias) + N'; INSERT INTO #ConvertedDates(Alias,dt,converted) VALUES(N' + QUOTENAME(#Alias,'''') + ',#dt,CONVERT(nvarchar(25),#dt));';
EXEC sys.sp_executesql #SQL, N'#dt datetime', #dt;
FETCH NEXT FROM Languages
INTO #Alias;
END;
CLOSE Languages;
DEALLOCATE Languages;
SELECT *
FROM #ConvertedDates;
DROP TABLE #ConvertedDates;
Yes, that is a Cursor. I wanted to ensure that each dynamic statement ran by itself, to ensure language was preserved for each conversion.

Concat a specific time, onto a date in Stored Procedure

I have an SSRS report where a user will choose a date range (2 dropdown). Inside the stored procedure I would like to use this date as passed, but append a specific time on the end of it.
I've been googling for a while and tried many things. But am not an expert and can't seem to land on a working solution
CURRENT CODE:
In my stored procedure, I capture the dates passed in:
ALTER PROCEDURE [dbo].[sp_JollySDKSkillChange]
#in_startdate datetime,
#in_enddate datetime
Then in the where clause ....
where dbo.JollySDKSkillChange.AddedDate between #in_startdate and #in_enddate
I need not only the date, but the start date should include 00:00:00 and the end date should include 23:59:59
How can I concatenate the specific times, onto the end of the date that is passed ?
At the moment, I do not get any results. But executing the stored procedure with a date and time together for each ... it provides the expected results.
You can modify the values after you receive them inside the stored procedure. Your #in_startdate should already be 00:00:00 because you've defined it as datetime, even if you only sent in a date.
ALTER PROCEDURE [dbo].[sp_JollySDKSkillChange]
#in_startdate datetime,
#in_enddate datetime
AS BEGIN
SET NOCOUNT ON;
SET #in_enddate = DATEADD(second,-1,dateadd(day,1,#in_enddate))
--Test values here
SELECT #in_startdate, #in_enddate
...
END

Error converting data type varchar to datetime. Need to return records based on the date or all records if no date is specified

I have implemented a storedprocedure and basically want the storedprocedure to return all records if no parameter is sent or records based on parameter sent. I am using date as the parameter. I am getting an error when executing exec [dbo].[getLog] '27/07/2017' . The error is
Error converting data type varchar to datetime.
Could somebody tell me what is incorrect in the logic
Create PROCEDURE [dbo].[getLog]
#dateFrom datetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT * from [CoreAnalytics].[dbo].[Logs]
where [TimeStamp] > ISNULL(#dateFrom, 0) ;
END
GO
If I understand you correct you want to return all records if #dateFrom is null, or filter on that variable.
I think you need something like this then
Create PROCEDURE [dbo].[getLog] #dateFrom datetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT * from [CoreAnalytics].[dbo].[Logs]
where (#dateFrom is null or [TimeStamp] > #dateFrom)
END
Make sure you are passing a valid datetime when calling the procedure.
It is best to use an universal format that will work with any database,
yyyyMMdd is a format that will always work.
http://karaszi.com/the-ultimate-guide-to-the-datetime-datatypes
exec [dbo].[getLog] '20170727'
should always work

Wrong time for same timezone in SQL Server 2005

I am passing param of type XML as a stored procedure param succesfully. I have no problems handling all the data from XML, but I discovered that dates from XML are not retrieved properly.
For example, 2013-03-14T15:14:53.598438+01:00 is now 2013-03-14 14:14:00. It seems that SQL is calculating +1 to display time.
I am using following T-SQL to get date from xml
select
A.B.value('xs:dateTime((ConfirmationDate)[1])', 'smalldatetime') as ConfirmationDate
FROM
#XML.nodes('/ArrayOfPreOrder/PreOrder/confirmationinfo/ConfirmationInfo') A(B)) as ConfirmationDate
How can I correct this issue? Both server and SQL Server are in the same timezone.
Check if there is a difference between your timezone setting and the timezone you're importing...
SELECT SYSDATETIMEOFFSET()
DECLARE #TimeZone NVARCHAR(255)
EXEC master.dbo.xp_instance_regread
N'HKEY_LOCAL_MACHINE',
N'SYSTEM\CurrentControlSet\Control\TimeZoneInformation',
N'TimeZoneKeyName',
#TimeZone OUTPUT
SELECT #TimeZone
You're specifying the timezone in the XML you're importing so I'm guessing it is converting it to local time for you. So your timezone would be +2 where you're importing from +1.

SQL Server 2008 Stored Procedure

I cannot store the date data type variables using stored procedure. My code is:
ALTER PROCEDURE [dbo].[Access1Register]
-- Add the parameters for the stored procedure here
#MobileNumber int,
#CitizenName varchar(50),
#Dob char(8),
#VerificationCode int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
select CAST(#dob As DATE)
Insert Into Access1 (MobileNo,CitizenName,Dob,VerificationCode)
values(#MobileNumber,#CitizenName,#Dob,#VerificationCode)
go
If I exec this procedure it is executing, but there is an error occured in the date type variable. It's raising the error as invalid item '-'.
It depends on how you pass in the #Dob values.
Your best bet is to use the ISO8601 format - 'YYYYMMDD' - since that will always convert to DATE properly - regardless of your language and regional settings on your SQL Server machine.
It depends on the date format that you pass.
If it is 'mm-dd-yy' you can use CONVERT(DATE, #Dob, 110), if it is 'dd-mm-yy' then CONVERT(DATE, #Dob, 105).
In which format you are passing the #Dob values? And what error you are getting exactly?
If you will pass the #Dob values in the format of mm-dd-yy, it should work correctly and no errors will be there.

Resources