I would like to know how I can translate this Oracle line into SQL Server code:
to_timestamp_tz('18/08/14 09:43:29,262000000 +02:00','DD/MM/RR HH24:MI:SSXFF TZR')
You can convert() to datetimeoffset() by replacing the comma with a period, and specifying a style that matches day first (if not already implicitly set by session settings and/or session language settings):
declare #str varchar(40) = '18/08/14 09:43:29,262000000 +02:00';
select convert(datetimeoffset(7),replace(#str,',','.'),4)
Or setting set dateformat dmy:
set dateformat dmy;
select convert(datetimeoffset(7),replace(#str,',','.'))
rextester demo: http://rextester.com/GSGL61143
Related
ALTER PROCEDURE [dbo].[AccountsData]
#Start_Date datetime,
#End_Date datetime
AS
BEGIN
SET NOCOUNT ON;
SELECT
a.Customer_AC_No, a.Customer_Name, a.Product_Code,
a.Product_Description, a.Sales_Person, c.HSID
FROM
(SELECT
Customer_AC_No, Customer_Name, Product_Code,
Product_Description, Sales_Person
FROM
View_Sales_Details
WHERE
([Week Ending] >=' #Start_Date') AND ([Sales Value] > 0)
GROUP BY
Customer_AC_No, Product_Code, Product_Description,
Customer_Name, Sales_Person) AS a
LEFT JOIN
(SELECT
Customer_AC_No, Product_Code
FROM
View_Sales_Details
WHERE
([Week Ending] >= '#End_Date') AND ([Sales Value] > 0)
GROUP BY
Customer_AC_No, Product_Code) AS b ON a.Customer_AC_No = b.Customer_AC_No
AND a.Product_Code = b.Product_Code
INNER JOIN
Hubspot.dbo.View_BPA_Cust_Data AS c ON a.Customer_AC_No = c.CustomerNo COLLATE Latin1_General_100_CI_AS
WHERE
b.Customer_AC_No IS NULL
ORDER BY
a.Customer_AC_No, a.Product_Code ASC
END
I am trying to pass the above date parameters to the SQL Server stored procedure above, but I keep getting this error
Msg 241, Level 16, State 1, Procedure AccountsData, Line 52
Conversion failed when converting date and/or time from character string.
Can some one please help. WeekEnding date is also in datetime format. Thanks
There are many formats supported by SQL Server for specifying a date&time as a string literal - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible.
So in your case, either switch to using DATE as your parameter datatype (since you obviously don't use the time portion):
ALTER PROCEDURE [dbo].[AccountsData]
#Start_Date DATE,
#End_Date DATE
and then execute your stored procedure like this:
EXEC [dbo].[AccountsData] '2019-05-11', '2020-06-10'
or use this format to support DATETIME if you insist on keeping that:
EXEC [dbo].[AccountsData] '2019-05-11T00:00:00', '2020-06-10T00:00:00'
Your have an error in your select. You have change your query like this
DATEPART(wk, Ending)>=DATEPART(wk, #Start_Date) AND ([Sales Value] > 0)
DATEPART(wk, Ending)>=DATEPART(wk, #End_Date) AND ([Sales Value] > 0)
This SQL Server stored procedure takes several parameters, and one of them is a datetime data type.
We've just began to localize the application in Europe, and the problem is that they're receiving this:
Error converting data type nvarchar to datetime.
I've done my reading on datetime, so I believe what is happening is the application is posting the date as dd/mm/yyyy to SQL Server, but since the database has a default language of English and expects mm/dd/yyyy, there is an error.
Sample input that produces error:
#LastUpdatedDate = N'21.01.2016 03:54:08'
My coworker in Europe said that when he set the default language of the database to German, the error quit occurring.
This error has not shown up in the USA/Canada, and I'm assuming that if the application AND SQL Server are running the same default datetime format, then no issues. However, we (here in USA), need to work with their application and database in Europe, so now we get the error.
Here's the stored procedure:
CREATE PROCEDURE [dbo].[addUser]
(
#UserID NVARCHAR ( 50 ),
#AccountID NVARCHAR( 50 ) = '00000000000000000000000000000000',
#Password NVARCHAR( 50 ),
#FirstName nvarchar(50),
#LastName nvarchar(50),
#Telephone nvarchar(25),
#Mobile nvarchar(25),
#FAX nvarchar(25),
#EmailAddress nvarchar(50),
#CurrentUserID nvarchar(50),
#LastUpdatedBy nvarchar(50),
#LastUpdatedDate datetime
)
AS
BEGIN TRANSACTION
INSERT INTO tbUsers (UserID, AccountID, Password, Status, VPID, EvalStatusID, FirstName, LastName, Telephone, Mobile, FAX, EmailAddress, LastUpdatedBy, LastUpdatedDate)
VALUES (#UserID, #AccountID, #Password, 'A', 'PM', 'ACTIVE', #FirstName, #LastName, #Telephone, #Mobile, #FAX, #EmailAddress, #LastUpdatedBy, #LastUpdatedDate)
I don't have access to the application code yet, but question is:
Is there a way to catch the error and fix the datetime input value depending on how database is configured?
I tried using SET DATEFORMAT dmy before the BEGIN TRANSACTION, but it errors out before that.
Yes, we could probably alter the application code to use a language-neutral datetime format, but that may not be feasible.
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible
Update: if you're on SQL Server 2012 or newer, you could use the new TRY_PARSE function in T-SQL which allows you to parse strings representing dates safely. You can specify a locale to use, and if the parse doesn't work, you get back a NULL instead of an exception.
Try this:
DECLARE #input NVARCHAR(100) = N'21.01.2016 03:54:08'
SELECT
TRY_PARSE(#input AS DATE USING 'en-gb')
Should return a valid DATE value of Jan-21, 2016 - no matter what language/locale your SQL Server is set to
I have set the SQL Server's default language to "British". The following correctly returns 23...
sp_configure 'default language'
I have also set the language of my login to "British" too with...
sp_defaultlanguage #loginame = 'Login123', #language = 'British'
However, when I attempt to specify 13/12/2015 as a DateTime stored procedure parameter from ASP Classic, I get...
Error converting data type nvarchar to datetime.
From Management Studio, with the correct login, it works.
Why would ASP Classic have this effect? I'm pretty sure it's using the correct connection string.
EDIT:
Its not the connection string. Somehow the date's format is being converted incorrectly before being sent to the database. I can see this from Profiler.
Use CONVERT with style:
British/French
103 = dd/mm/yyyy
SELECT CONVERT(DATETIME, '13/12/2015', 103);
-- with stored procedure
DECLARE #d DATETIME = CONVERT(DATETIME, '13/12/2015', 103);
EXEC [dbo].[my_stored_procedure] #d;
Another method is to use ISO 8601 date literal which is culture independent:
The advantage in using the ISO 8601 format is that it is an international standard. Also, datetime values that are specified by using this format are unambiguous. Also, this format is not affected by the SET DATEFORMAT or SET LANGUAGE settings.
yyyy-mm-ddThh:mm:ss[.mmm]
EXEC [dbo].[my_stored_procedure] '2015-12-13T00:00:00'
If you want to set the dateformat to some style say, ddMMyyyy, in sql server we can use the following statement:
SET DATEFORMAT dmy
My question is how to know before hand that this is the format set?
The program I am writing needs to determine, if the above is the actual datetimeformat, else set it and continue with rest of execution.
How is this possible? Else is my only approach, to set it to my desired format and continue with execution?
I hope setting this won't affect other sessions (connections)?
To check the date format use
DBCC useroptions
SET DATEFORMAT will only effect the current session
MSDN Link
the below code, get the current session dateformat, sets it and test if it is working
-- get the current session date_format
select date_format
from sys.dm_exec_sessions
where session_id = ##spid
-- set the dateformat for the current session
set dateformat ymd
-- this should work
select cast('2017-08-13 16:31:31' as datetime)
Starting with SQL 2008, the current date format setting can be determined by SPID/session_id within the dm_exec_requests dynamic management view:
SELECT r.date_format
FROM master.sys.dm_exec_requests r
WHERE r.session_id = ##SPID;
Permissions:
If the user has VIEW SERVER STATE permission on the server, the user is able to see all executing sessions on the instance of SQL Server; otherwise, the user will see only the current session.
It seems there is not a global ## variable to display DATEFORMAT. (?)
The list of ## variables is documented here:
https://learn.microsoft.com/en-us/sql/t-sql/functions/configuration-functions-transact-sql?redirectedfrom=MSDN&view=sql-server-ver15
As per other answers here,
Can use:
DBCC useroptions
and
select date_format
from sys.dm_exec_sessions
where session_id = ##spid
You should convert datetime to desirable format by convert function,
Try this:
SELECT convert(varchar(10),getdate(),103)
OR
SELECT replace(convert(varchar(10),getdate(),103),'/','')
yo can get more information on:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
I need to change the date format from US (mm/dd/YYYY) to UK (dd/mm/YYYY) on a single database on a SQL server machine.
How can this be done?
I've seen statements that do this for the whole system, and ones that do it for the session, but I can't change the code now as it will have to go through QA again, so I need a quick fix to change the date time format.
Update
I realize that the date time has nothing to do with how SQL Server stores the data, but it does have a lot to do with how it parses queries.
I'm chucking raw data from an XML file into a database. The dates in the XML file are in UK date format.
You could use SET DATEFORMAT, like in this example
declare #dates table (orig varchar(50) ,parsed datetime)
SET DATEFORMAT ydm;
insert into #dates
select '2008-09-01','2008-09-01'
SET DATEFORMAT ymd;
insert into #dates
select '2008-09-01','2008-09-01'
select * from #dates
You would need to specify the dateformat in the code when you parse your XML data
In order to avoid dealing with these very boring issues, I advise you to always parse your data with the standard and unique SQL/ISO date format which is YYYY-MM-DD. Your queries will then work internationally, no matter what the date parameters are on your main server or on the querying clients (where local date settings might be different than main server settings)!
You can only change the language on the whole server, not individual databases. However if you need to support the UK you can run the following command before all inputs and outputs:
set language 'british english'
Or if you are having issues entering datatimes from your application you might want to consider a universal input type such as
1-Dec-2008
Although you can not set the default date format for a single database, you can change the default language for a login which is used to access this database:
ALTER LOGIN your_login WITH DEFAULT_LANGUAGE=British
In some cases it helps.
If this really is a QA issue and you can't change the code. Setup a new server instance on the machine and setup the language as "British English"
Use:
select * from mytest
EXEC sp_rename 'mytest.eid', 'id', 'COLUMN'
alter table mytest add id int not null identity(1,1)
update mytset set eid=id
ALTER TABLE mytest DROP COLUMN eid
ALTER TABLE [dbo].[yourtablename] ADD DEFAULT (getdate()) FOR [yourfieldname]
It's working 100%.
You do realize that format has nothing to do with how SQL Server stores datetime, right?
You can use set dateformat for each session. There is no setting for database only.
If you use parameters for data insert or update or where filtering you won't have any problems with that.
For SQL Server 2008 run:
EXEC sp_defaultlanguage 'username', 'british'