Inserting date in sql server - sql

When I try to execute this query
INSERT INTO StateRegion
( FullName ,
Abbreviation ,
RegionType ,
Admitted ,
Capital
)
VALUES ( 'Alabama' ,
'AL' ,
1 ,
'1819-Dec-14' ,
'Montgomery'
);
it gives me error sql date conversion error :
Conversion failed when converting date and/or time from character
string
Admitted is a Date type.
The issue is I can not change this format : 1819-Dec-14, is it possible to add convert method to the query above ?
Table definition :
CREATE TABLE StateRegion
(
ID bigint PRIMARY KEY IDENTITY(1,1),
FullName varchar(50) NOT NULL,
Abbreviation varchar(2) NOT NULL,
RegionType smallint NOT NULL,
Admitted date NULL,
Capital varchar(50) NULL
);

The month name part of that date format is interpreted according to the language of the login.
You can change the default language of the login to US English or British English if you must work with that format or issue a
Set language english
To set the format at run time before the problematic query then optionally switch it back afterwards.
If you have the choice using yyyy-mm-dd or yyyymmdd would be preferable formats for date literals though that both avoid this issue when casting to date.

Use a parameterized query. Parameterization will send the date to the server in binary, avoiding any string conversions which depend upon the client locale.
Example in C#:
SqlCommand sqc = new SqlCommand("INSERT INTO MyTable (DateColumn) VALUES (#date)", con);
sqc.Parameters.AddWithValue("#date", new DateTime(1819, 12, 14));
If you are running this from an interactive batch (SQL Server Management Studio, or similar), use SET LANGUAGE to ensure the dates are parsed correctly:
SET LANGUAGE ENGLISH;
INSERT INTO StateRegion (FullName, Abbreviation, RegionType, Admitted, Capital)
VALUES ('Alabama', 'AL', 1, '1819-Dec-14', 'Montgomery');
SqlFiddle example showing correct parsing

Do not confuse storage format and display format. Just because the server store the date in the database as '1819-12-14' you can use a custom formatting output for the display.
Then correct for the display issue with a function such as:
CREATE FUNCTION usp_FormatedDateString (#Date Date)
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE #RETURN AS VARCHAR(50)
DECLARE #I INT = 0
DECLARE #M AS VARCHAR(100) = 'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'
SET #RETURN = CAST(DATEPART(YEAR,#Date) AS VARCHAR(4))
SET #I = DATEPART(MONTH, #Date) - 1
SET #RETURN = #RETURN + '-' + SUBSTRING(#M,(#I*3)+1,3)+'-'+ CAST (DATEPART(DAY,#Date) AS VARCHAR(2))
RETURN #RETURN
END
GO
Then when you display the results:
SELECT FullName,Abbreviation,RegionType, dbo.usp_FormatedDateString (Admitted) as Admitted, Capital FROM StateRegion
It will display correct and store correctly.

You can try to use an explicit format for the conversion. You are not explaining why you can't change the format, but I imagine that you are reading the values somehow that are already stored as that. You can use CONVERT:
DECLARE #Admitted VARCHAR(11);
SET #Admitted = '1819-Dec-14'
SELECT CONVERT(DATETIME,RIGHT(#Admitted,2)+' '+
SUBSTRING(#Admitted,6,3)+' '+
LEFT(#Admitted,4),106);

Chang datatype of date to VARCHAR

Related

Temporarily change format of a date column in SQL Query output MM/YY -> MM/DD/YYYY

I have data on my SQL Server that is formatted like so:
06/21
MM/YY
I would like to manipulate it so that all the dates are displayed as MM/DD/YYYY. So as the previous example it would look like:
06/01/2021
I was wondering if there is some sort of function that I can run in my query to display the date column differently in my output? I don't want to actually alter the way in which the Column is formatted on the back end, I just want to change how it is presented to the user in the results of a single query.
Thank you for your help!
Using STUFF
declare #var varchar(64) = '06/21 '
select stuff(#var,4,0,'01/20')
So for your table.
select stuff(yourColumn,4,0,'01/20')
From yourTable
Just replace / with 01/20:
declare #yourDate varchar(10) = '06/21'
select replace(#yourDate ,'/','/01/20')
Result:
But it is probably wiser to cast it to a proper date type:
declare #yourDate varchar(10) = '06/21'
select cast(replace(#yourDate ,'/','/01/20') as date)
you can use this solution
it works with all years 1998, .. 2000,2001 ...
declare #theDate varchar(10) = '06/21'
select convert(date,'01/'+ #theDate ,3)

SQL Server : convert nvarchar year to datetime

I am trying to convert nvarchar(5) year of birth (e.g. 1972) to a datetime (e.g. 1972-06-01) in a SQL Server table.
Something like:
UPDATE TableName
SET DateOfBirth = CONVERT(datetime, YearOfBirth + '/01/01', 103)
This throws an error
Conversion failed when converting date and/or time from character string
How can I solve this?
What you are doing needs two steps: store the value in the column as a date and then change the type.
In your case, a third step is needed, so the column is big enough to store the value string representation of the date value. I think this will work in SQL Server:
ALTER TABLE TableName ALTER COLUMN DateOfBirth NVARCHAR(32);
UPDATE TableName
SET DateOfBirth = YearOfBirth + '-01-01';
ALTER TABLE TableName ALTER COLUMN DateOfBirth Date;
The first ALTER TABLE alters the column to be wide enough for the new month and day. Then the date is constructed in a standard format (okay, leaving out the hyphens would be even more standard). Then the column is transformed to a date.
If you just want something that looks like a date -- and a lot of criticism on Stack Overflow ;) -- you can eliminate the third step.
This is all you need
UPDATE TableName
SET DateOfBirth = YearOfBirth + '-06-01'
Where YearOfBirth = '1972'

Using SQL 2005 trying to cast 16 digit Varchar as Bigint error converting

First, thanks for all your help! You really make a difference, and I GREATLY appreciate it.
So I have a Varchar column and it holds a 16 digit number, example: 1000550152872026
select *
FROM Orders
where isnumeric([ord_no]) = 0
returns: 0 rows
select cast([ord_no] as bigint)
FROM Progression_PreCall_Orders o
order by [ord_no]
returns: Error converting data type varchar to bigint.
How do I get this 16 digit number into a math datatype so I can add and subtract another column from it?
UPDATE: Found scientific notation stored as varchar ex: 1.00054E+15
How do I convert that back into a number then?
DECIMAL datatype seems to work fine:
DECLARE #myVarchar AS VARCHAR(32)
SET #myVarchar = '1000550152872026'
DECLARE #myDecimal AS DECIMAL(38,0)
SET #myDecimal = CAST(#myVarchar AS DECIMAL(38,0))
SELECT #myDecimal + 1
Also, here's a quick example where IsNumeric returns 1 but converting to DECIMAL fails:
DECLARE #myVarchar AS VARCHAR(32)
SET #myVarchar = '1000550152872026E10'
SELECT ISNUMERIC(#myVarchar)
DECLARE #myDecimal AS DECIMAL(38,0)
SET #myDecimal = CAST(#myVarchar AS DECIMAL(38,0)) --This statement will fail
EDIT
You could try to CONVERT to float if you're dealing with values written in scientific notation:
DECLARE #Orders AS TABLE(OrderNum NVARCHAR(64), [Date] DATETIME)
INSERT INTO #Orders VALUES('100055015287202', GETDATE())
INSERT INTO #Orders VALUES('100055015287203', GETDATE())
INSERT INTO #Orders VALUES('1.00055015287E+15', GETDATE()) --sci notation
SELECT
CONVERT(FLOAT, OrderNum, 2) +
CAST(REPLACE(CONVERT(VARCHAR(10), GETDATE(), 120), '-', '') AS FLOAT)
FROM #Orders
WITH validOrds AS
(
SELECT ord_no
FROM Orders
WHERE ord_no NOT LIKE '%[^0-9]%'
)
SELECT cast(validOrds.ord_no as bigint) as ord_no
FROM validOrds
LEFT JOIN Orders ords
ON ords.ord_no = validOrds.ord_no
WHERE ords.ord_no is null
Take a look at this link for an explanation of why isnumeric isn't functioning the way you are assuming it would: http://www.sqlservercentral.com/articles/IsNumeric/71512/
Take a look at this link for an SO post where a user has a similar problem as you:
Error converting data type varchar
hence, you should always use the correct datatype for each column unless you have a very specific reason to do so otherwise... Even then, you'll need to be extra careful when saving values to the column to ensure that they are indeed valid values

How to enter a Date into a table in TSQL? (Error converting data type varchar to datetime)

I want to enter 30/10/1988 as the date to a DOB column in a table using a procedure
alter procedure addCustomer
#userName varchar(50),
#userNIC varchar(50),
#userPassword varchar(100),
#userDOB datetime,
#userTypeID int,
#userEmail varchar(50),
#userTelephone int,
#userAddress char(100),
#userCityID int,
#status int output
as
declare #userID int
declare #eid int
declare #tid int
declare #aid int
execute getLastRaw 'userID','tblUserParent', #userID output
insert into tblUserParent values (#userID, #userName, #userNIC, #userPassword, #userDOB, #userTypeID)
execute getLastRaw 'addressID','tblAddress', #aid output
insert into tblAddress values (#aid, #userAddress, #userID, #userCityID)
execute getLastRaw 'emailID','tblEmail', #eid output
insert into tblEmail values (#eid, #userEmail, #userID)
execute getLastRaw 'telephoneID','tblTelephoneNO', #tid output
insert into tblTelephoneNO values (#tid, #userTelephone , #userID)
insert into tblUserCustomer values (#userID, #eid , #tid, #aid)
...but it gives an error when i enter like this '30/10/1988'
Msg 8114, Level 16, State 5, Procedure addCustomer, Line 0 Error converting data type varchar to datetime.
...but when I enter like only the 30/10/1988
Incorrect syntax near '/'
How do I fix this?
If you would truly like to avoid the possibility of ambiguous dates based, then you should always enter it in one of the two unambiguous date formats Answer has already been selected and it's valid but I'm a believer in spreading the knowledge ;)
As noticed by #cloud and my post representing a younger, and less wise me with a link only answer, I'll pop the contents of the archive of Jamie Thompson's answer for unambiguous date formats in TSQL
tl;dr;
yyyy-MM-ddTHH24:mi:ss
yyyyMMdd HH24:mi:ss
One of the most commonly used data types in SQL Server is [datetime]
which unfortunately has some vagaries around how values get casted. A
typical method for defining a [datetime] literal is to write it as a
character string and then cast it appropriately. The cast syntax looks
something like this: DECLARE #dt NVARCHAR(19) = '2009-12-08 18:00:00';
SELECT CAST(#dt AS datetime);
Unfortunately in SQL Server 2005 the result of the cast operation may
be dependent on your current language setting. You can discover your
current language setting by executing: SELECT ##LANGUAGE To
demonstrate how your language setting can influence the results of a
cast take a look at the following code: ALTER DATABASE tempdb
SET COMPATIBILITY_LEVEL = 90 ; --Behave like SQL Server 2005
USE tempdb
GO
DECLARE #t TABLE (
dateString NVARCHAR(19)
);
INSERT #t (dateString)
VALUES ('2009-12-08 18:00:00') --'yyyy-MM-dd hh24:mi:ss'
, ('2009-12-08T18:00:00') --'yyyy-MM-ddThh24:mi:ss'
, ('20091208 18:00:00') --'yyyyMMdd hh24:mi:ss'
SET LANGUAGE french;
SELECT 'french' AS lang
, DATENAME(MONTH,q.[dt]) AS mnth
, q.[dt]
FROM (
SELECT CAST(dateString AS DATETIME) AS dt
FROM #t
)q;
SET LANGUAGE us_english;
SELECT 'us_english' AS lang
, DATENAME(MONTH,q.[dt]) AS mnth
, q.[dt]
FROM (
SELECT CAST(dateString AS DATETIME) AS dt
FROM #t
)q; We are taking the value which can be described in words as “6pm on 8th December 2009”, defining it in three different ways, then
seeing how the ##LANGUAGE setting can affect the results. Here are
those results: french language datetime Notice how the interpretation
of the month can change depending on ##LANGUAGE. If
##LANGUAGE=’french’ then the string '2009-12-08 18:00:00' is
interpreted as 12th August 2009 (‘août’ is French for August for those
that don’t know) whereas if ##LANGUAGE=’us_english’ it is interpreted
as 8th December 2009. Clearly this is a problem because the results of
our queries have a dependency on a server-level or connection-level
setting and that is NOT a good thing. Hence I recommend that you only
define [datetime] literals in one of the two unambiguous date formats:
yyyy-MM-ddTHH24:mi:ss yyyyMMdd HH24:mi:ss That was going to be the end
of this blog post but then I found out that this behaviour changed
slightly in SQL Server 2008. Take the following code (see if you can
figure out what the results will be before I tell you): ALTER
DATABASE tempdb
SET COMPATIBILITY_LEVEL = 100 ; --Behave like SQL Server 2008
GO
USE tempdb
GO
SET LANGUAGE french;
DECLARE #dt NCHAR(10) = '2009-12-08 18:00:00'; --Ambiguous date
format
SELECT CAST(#dt AS datetime) AS [ExplicitCast]
, DATENAME(MONTH,#dt) AS [MonthFromImplicitCast]
, DATENAME(MONTH,CAST(#dt AS datetime)) AS
[MonthFromExplicitCast]; Here we are doing three different things with
our nchar literal: explicitly cast it as a [datetime] extract the
month name from the char literal using the DATENAME function (which
results in an under-the-covers implicit cast) extract the month name
from the char literal using the DATENAME function after it has been
explicitly casted as a [datetime] Note that the compatibility level is
set to SQL Server 2008 and ##LANGUAGE=’french’. Here are the results:
image (Were you correct?) Let’s take a look at what is happening here.
The behaviour when we are explicitly casting as [datetime] hasn’t
changed, our nchar literal is still getting interpreted as 12th August
rather than 8th December when ##LANGUAGE=’french’. The
[MonthFromExplicitCast] field is interesting though, it seems as
though the implicit cast has resulted in the desired value of 8th
December. Why is that? To get the answer we can turn to BOL’s
description of the DATENAME function syntax: image The implicit cast
is not casting to [datetime] at all, it is actually casting to [date]
which is a new datatype in SQL Server 2008. The new date-related
datatypes in SQL Server 2008 (i.e. [date], [datetime2], [time],
[datetimeoffset]) disregard ##LANGUAGE and hence we get behaviour that
is more predictable and, frankly, better. These new behaviours for SQL
Server 2008 were unknown to me when I began this blog post so I have
learnt something in the course of authoring it, I hope it has helped
you too. No doubt someone somewhere is going to get nastily burnt by
this at some point, make sure that it isn’t you by always using
unambiguous date formats: yyyy-MM-ddTHH24:mi:ss yyyyMMdd HH24:mi:ss
regardless of which version you are on!
The following works in both SQL Server and MySql without ambiguity: yyyy-mm-dd, like so:
INSERT INTO TableName(DateColumn) VALUES ('1988-10-30');
...as an added benefit there's no question of whether it's a US or European style date on days like the fourth of March...
See if there is a culture setting that you can change to allow you to use dd/mm/yyyy. I believe it is expecting mm/dd/yyyy.
A potentially easy way around the problem is to use a date format with no ambiguity between mm/dd/yyyy and dd/mm/yyyy such as dd-mmm-yyyy, eg: 30-OCT-1988

bulk insert datetime data

I try to bulk insert some datetime values in this format:
31/12/2005 00:00:00
using something like this:
create table Seed
(
StartDate datetime not null
)
BULK INSERT Seed
FROM 'd:\dump\Seed.txt'
WITH
(
firstrow=2,
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
)
But I get this:
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row
I know how to define a codepage but which? Is there a simple solution?
Thanks.
Christian
What is the default language for the user logged in to the SQL instance while running this T-SQL? The date format you specified 31/12/2005 00:00:00 looks to be British and perhaps your default language is US_English.
Try running this T-SQL to determine your current language:
SELECT ##language, ##langid
If it's US_English, then your date format should be mm/dd/yyyy hh:mm:ss
To keep your example alive, try changing your default language for the current user by doing the following:
--Get the current language setting for connected user
SELECT ##LANGUAGE,##LANGID
--Get information about all languages
EXEC sys.sp_helplanguage
--Get the name of the current user
DECLARE #sysuser NVARCHAR(30)
SET #sysuser = SYSTEM_USER
PRINT #sysuser
EXEC sp_defaultlanguage #sysuser, 'british' --satisfying your example date
After you have changed the default language, reconnect your query window and you should be now utilizing the new default language.
To get back to the previous language setting, just EXEC sp_defaultlanguage again with the language setting you previously had.
Hopefully that works!
SQL Server is not going to convert the DD/MM/YYYY date format correctly. You'll need to either reformat your input file as MM/DD/YYYY or insert into a char/varchar datatype and then manipulate the string into the correct format for another datetime column. For example:
create table TempSeed
(
StartDate varchar(50) not null
)
BULK INSERT TempSeed
FROM 'd:\dump\Seed.txt'
WITH
(
firstrow=2,
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
)
create table Seed
(
StartDate datetime not null
)
insert into Seed
(StartDate)
select CAST(substring(ts.StartDate,4,3) + stuff(ts.StartDate,4,3,'') as datetime)
from TempSeed ts