Inserting CDate to SQL Server 2012 Flip Day and Month - sql-server

I have a problem inserting a date from a VB.net Program to a SqlServer2012 instance.
First here is how i generate the data (Vb.net)
ExitTime = CDate("1.1.1970 00:00:00").AddSeconds(currentField).ToLocalTime
We add this value to a stored procedure (Vb.net)
With comsql5.Parameters.AddWithValue("#ExitTime", ExitTime)
In the Sql Server stored procedure
#ExitTime datetime, [...]
[...]
Insert into [table] ([ExitTime]) VALUES (#ExitTime)
Here is the output of the exit time in the vb.net
Exit Time : 08/07/2014 2:06:31 PM
Here is the same row in the Sql server database
2014-08-07 14:06:31.000
What I would like to see in the database is 2014-07-08 14:06:31.00
Because another part in the program does a check on the field but as a String... and it does not match because it flip the month and day
EDIT: TO be clear, I can't change the other part that does the comparison as a string. I know this is a poor way to compare datetime.
Thank for your time

Have you tried using the Convert function?
SELECT CONVERT (VARCHAR, getdate(), 121);
Check this links for more information MSDN - CAST and CONVERT and SQL Server Datetime Format

Related

SQL Server SQL to PostgreSQL SQL

I need to convert the following SQL server code to PostgreSQL code.
Any help would be appreciated.
SQL Server SQL:
CAST(DATEADD(ww,DATEDIFF(ww,0,trans_date),-1)as date) as week
I think what that code does is to "round" the value of trans_date to the beginning of the week. In Postgres you can do that using the date_trunc() function:
date_trunc('week', trans_date)
Note that this always returns a timestamp, if you need a real date value, cast the result:
date_trunc('week', trans_date)::date
If it should be the day before the beginning of the week, just subtract one day from the result:
date_trunc('week', trans_date)::date - 1

Why does SQL server's Date format affect date conversions with Timestamps

I'm trying to convert a varchar containing a date into a datetime field in SQL server using the following script
SELECT cast('2017-12-14 14:30:41.007' as datetime)
When I ran this on my local Machine that uses DateFormat myd this worked fine and returned a valid datetime.
When I ran this statement on my server that uses Dateformat dym the server returned the following error
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Why is '2017-12-14 14:30:41.007' a valid datetime under "myd" but not under "dym" even though it's neither a "dym" nor a "myd" date?
I have found a work around for the issue btw, I'm asking because i want to understand what is going on in SQL server
It is because SQL server is interpreting 14 as a month number and there are only 12 months. If you change the 14 to 11 and run this script you will see the difference:
SET DATEFORMAT myd
SELECT DATEPART(month,cast('2017-12-11 14:30:41.007' as datetime))
SET DATEFORMAT dym
SELECT DATEPART(month,cast('2017-12-11 14:30:41.007' as datetime))
/*
Output:
12
11
*/
To make things consistent for all time formats put a T in the middle of the date and time. This makes SQL server think the date is in ISO8601 format.
SET DATEFORMAT myd
SELECT DATEPART(month,cast('2017-12-11T14:30:41.007' as datetime))
SET DATEFORMAT dym
SELECT DATEPART(month,cast('2017-12-11T14:30:41.007' as datetime))
/*
Output:
12
12
*/
'2017-12-14 14:30:41.007' seems to follow ODBC canonical with milliseconds default standard for time, date, datetime2, and datetimeoffset. If you are using MS SQL you can use CONVERT to cope with the specific style of the string parameter:
SELECT convert(datetime,'2017-12-14 14:30:41.007' , 121 )

SQL Server - Calculate Age from date of birth in Varchar

Using SQL Server 2008 R2
I have a database of my friend's project. He used varchar to store date of birth of members because he was getting errors parsing entries to date. I want to show the age using a procedure code.
the format of date stored in mm/dd/yyyy where today's date is stored as 3/4/2016 . I wanted to use DATEDIFF function but it is not a good option with varchar.
Create procedure spCalculateAge
#dob varchar(10)
as
Begin
Select DATEDIFF(year,Convert(date,#dob),getdate()) as Age
End
I used this and it worked. Before it was giving conversion error but opening and closing SQL Server caused it to work.

what is the best way to insert only datepart of system date into SQL Server

I'm currently using
Convert(varchar, Getdate(), 101)
to insert only date part of system date into one of my sql server database tables.
my question is: is it the right way to do that or is there any other better method to do it?
I don't understand why you're converting the GETDATE() output (which is DATETIME already) to a VARCHAR and then SQL Server would convert it back to DATETIME upon inserting it again.
Just use:
INSERT INTO dbo.YourTable(SomeDateTimeColumn)
VALUES(GETDATE())
If you're doing that conversion to get rid of the time portion of the DATETIME, you should better:
use the DATE datatype (available in SQL Server 2008 and newer) to store only the DATE (no time)
if you're using SQL Server 2005 or earlier, use this conversion instead - should be much more efficient than two conversions!
INSERT INTO dbo.YourTable(SomeDateTimeColumn)
VALUES(DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0))
Update: did some performance testing, and in this particular case, it seems the amount of work that SQL Server needs to do is really the same - regardless of whether you're using the convert to varchar stripping the time and back to datetime approach that you already have, or whether you're using my get the number of days since date 0 approach. Doesn't seem to make a difference in the end.
The BEST solution however would still be: if you only need the date anyway - use a column of type DATE (in SQL Server 2008 and newer) and save yourself any conversions or manipulations of the GETDATE() output altogether.

bulk insert a date in YYYYMM format to date field in MS SQL table

I have a large text file (more than 300 million records). There is a field containing date in YYYYMM format. Target field is of date type and I'm using MS SQL 2008 R2 server. Due to huge amount of data I'd prefer to use bulk insert.
Here's what I've already done:
bulk insert Tabela_5
from 'c:\users\...\table5.csv'
with
(
rowterminator = '\n',
fieldterminator = ',',
tablock
)
select * from Tabela_5
201206 in file turns out to be 2020-12-06 on server, whereas I'd like it to be 2012-06-01 (I don't care about the day).
Is there a way to bulk insert date in such format to a field of date type?
kind regards
maciej pitucha
Run SET DATEFORMAT ymd before the bulk insert statement
Note that yyyy-mm-dd and yyyy-dd-mm are not safe in SQL Server generally: which causes this. Always use yyyymmdd. For more, see best way to convert and validate a date string (the comments especially highlight misunderstandings here)
There isn't a way to do this on Bulk Insert. You have 2 options.
Insert the date as into a varchar field then run a query to convert
the date into a DateTime field
Use SSIS
You may not care about the day but SQL does.
YYYYMM is not a valid SQL date.
A date must have day component.
In your example it parsed it down as YYMMDD.
You could insert into a VarChar as Jaimal proposed then append a 01 and convert.
I would read in the data in .NET add the 01 and use DateTime.ParseExact and insert row by row asynch. You can catch any parse that is not successful.
Or you might be able to do a global replace in the csv "," to "01,". It is worth a try.

Resources