How to make SQL internal functions default to ISO 8061 format - sql

Microsoft SQL Server 2016 (RTM) - 13.0.1601.5 (X64)
Copyright (c) Microsoft Corporation Express Edition (64-bit) on Windows 10 Pro 6.3 (Build 14393)
Server Collation: SQL_Latin1_General_CP1_CI_AS
Language: English (United States)
I'm using internal getdate() function to automatically fill a DateCreated column of DATE datatype.
As a matter of fact when a new product is entered I can see date values are being created in table in MM/dd/YYYY format (i.e. 3/18/2017).
Why is that? Is there a way to force getdate() to use the ISO 8061 format?
CREATE TABLE [dbo].[Products]
(
[ID] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Description] NVARCHAR (500) NOT NULL,
[IsDeleted] BIT NOT NULL,
[IsApproved] BIT NOT NULL,
[CategoryID] INT NOT NULL,
[UserID] NVARCHAR (MAX) NOT NULL,
[DateCreated] DATE DEFAULT (getdate()) NULL,
[DateExpire] DATE CONSTRAINT [CONSTRAINT_NAME] DEFAULT (dateadd(month,(1),getdate())) NULL,
[DateLastModified] DATE DEFAULT (getdate()) NULL,
CONSTRAINT [PK_dbo.Products]
PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_dbo.Products_dbo.Categories_CategoryID]
FOREIGN KEY ([CategoryID]) REFERENCES [dbo].[Categories] ([ID])
);

The value of date and datetime data type is not stored with format in sql server. If you want to see the date in a different format you can manipulate the way that date and datetime data types are displayed when converted to a varchar (or nvarchar,nchar,char) data type using some built in functions.
Most often with convert() styles
select convert(varchar(10),getdate(),120)
returns: 2017-03-19
In sql server 2012+ you can use format()
select format(getdate(),'yyyy-MM-dd')
returns: 2017-03-19
But format() can be slower, take a look here: format() is nice and all, but… - Aaron Bertand

The format is not set in the data as stored for the date data types.
You can however set the format to be used for the visual display of dates.
SET DATEFORMAT { format | #format_var }
-- For example set date format to day/month/year.
SET DATEFORMAT dmy;
GO
format | #format_var
Is the order of the date parts. Valid parameters are mdy, dmy, ymd, ydm, myd, and dym.
Note ydm is not supported for date, datetime2 and datetimeoffset data types.
Just to add clarity this differs from the date and time styles format as as varchar for instance in:
CONVERT(VARCHAR(20), GETDATE(), 100)

Related

Microsoft SQL Constraint Check for Year higher than 2000

I'm creating a database and I want to create a Constraint Check that only allows to insert Dates that are after year 2000.
This is where i store dates:
CREATE TABLE User (
username varchar(20) NOT NULL,
birthdate DATE NOT NULL,
CONSTRAINT user_birthdate_ck CHECK (birthdate > 2000)
)
2000 is not a date, it's a number.
You need to specify a date in quotes using an unambiguous date format. Best to use 'YYYYMMDD'.
CREATE TABLE [User] (
username varchar(20) NOT NULL,
birthdate DATE NOT NULL,
CONSTRAINT user_birthdate_ck CHECK (birthdate > '20000101')
);
db<>fiddle
Assuming you actually wanted after the year 2000 then you probably want
CONSTRAINT user_birthdate_ck CHECK (birthdate >= '20010101')
Do not use > '20001231' if you have a time component as it won't be correct.
Change the year to a properly formed date as follows:
CONSTRAINT user_birthdate_ck CHECK (birthdate > '2000/12/31')
It would also be prudent to explicitly set the date format being used before the CREATE TABLE as follows:
SET DATEFORMAT ymd;
GO
BEWARE all the strings expression of dates showns in answers are not in the ISO SQL format and won't do the job under certain session parameters like language or some others, espcially mixed with non Transct SQL in a batch...
The only string format that never cause you any trouble is the SQL ISO long date format as :
'AAAA-MM-JJ'

SQL: how to specify a date format on creating a table and fill it

I want to save the date in format 'dd.mm.yyyy'. So I read there are different formats for a date in SQL (by the way I use Visual Studio and SQL Server).
I tried this code:
CREATE TABLE APP(
ID INT NOT NULL,
DT DATE FORMAT 'dd.mm.yyyy',
ADDRESS NVARCHAR (100) ,
PRIMARY KEY (ID)
);
But it returns the error:
Incorrect syntax near 'FORMAT'.
After that I want to use this code:
INSERT INTO APP (ID, DT)
VALUES ('1','22.12.2016')
You don't need to specify the format in the table definition as dates are stored in a binary format.
CREATE TABLE APP(
ID INT NOT NULL,
DT DATE,
ADDRESS NVARCHAR (100) ,
PRIMARY KEY (ID)
);
When you try to insert into that table however, the server will try to convert the string to a date before inserting it. This can be problematic as it is unable to tell if 12.11.2017 is the 12th of November or 11th of December. To figure this out it uses the localization settings of the user account that is performing the operation.
Often you will find that the account that is running the operation is set to USA format, month day then year (MDY), when what you want is day month year (DMY) format. One way to tell it what the sequence of the date's parts is to use the DATEFORMAT setting like this:
SET DATEFORMAT dmy;
INSERT INTO APP (ID, DT)
VALUES (1,'22.12.2016')
Another alternative is to cast the string to a date using the CONVERT function and tell it what the date format is. The formats have numeric codes like 104 for German format Like this:
INSERT INTO APP (ID, DT)
VALUES (2,CONVERT(date,'22.12.2016',104))
Dates are stored in an internal format. Formats only make sense for input and output.
In your case you want the date in a German format (104), so you can use:
select convert(varchar(255), dt, 104)
If you like, you can include the formatted date as a separate column:
CREATE TABLE APP (
ID INT NOT NULL,
DT DATE,
ADDRESS NVARCHAR(100),
DT_FORMATTED AS (convert(varchar(255), dt, 104)),
PRIMARY KEY (ID)
);
You can then refer to dt_formatted to get the string in the format you want.
Use this:
CREATE TABLE APP(
ID INT NOT NULL,
DT DATE ,
ADDRESS NVARCHAR (100) ,
PRIMARY KEY (ID)
);
Its default setting is yyyy-MM-dd.
No, it's not. There is no formatting information at all associated with the field.
The value is not formatted by the database. It's returned only as a point in time. Formatting that value into its textual representation is done by the application that is getting the data from the database.
So, there is nothing that you can do in the database to change how the date value is formatted. You have to change that where the data is displayed.
Dates are stored in an internal format.
Formats only make sense for input and output.
You can include the formatted date as a separate column:
SQL Server supports the date format. You have to use the below date format.
With century (yyyy) | Standard | Input/Output
103 | British/French | 103 = dd/mm/yyyy
CREATE TABLE [dbo].[Post]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] VARCHAR(MAX) NULL,
[RowNo] INT NULL,
[ColNo] INT NULL,
[Deadline] (CONVERT(VARCHAR(255), dt, 103)), -- Include the formatted date as a separate column
CONSTRAINT [PK_KtoCo]
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Use this.
CREATE TABLE:
CREATE TABLE EMP
(EID NUMBER(20),
ENAME VARCHAR2(20),
DT DATE,
SAL NUMBER(20));
INSERT INTO THE TABLE:
INSERT INTO EMP (EID,ENAME,DT,SAL) VALUES(01,'ABCDE','11.NOV.2011',10000);
O/P OF ABOVE TABLE:
SELECT * FROM EMP;
EID ENAME DT SAL
01 ABCDE 11-DEC-11 10000

sql conversion of a varchar data type to a datetime data type out-of-range

I am trying to add to a table a group of values on of them is a date.
When trying to add a date i receive the following error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
i have tried to run the following query's:
INSERT INTO BoxEntries (Date,Value,Description,Empid,EmpName) Values(CAST('27/07/2017 10:24:13' AS DATETIME),'0','Alpha Day','0','Alpha')
INSERT INTO BoxEntries (Date,Value,Description,Empid,EmpName) Values(CONVERT(VARCHAR,'27/07/2017 10:24:13',13),'0','Alpha Day','0','Alpha')
INSERT INTO BoxEntries (Date,Value,Description,Empid,EmpName) Values(CONVERT(VARCHAR,'27-07-2017 10:24:13.000',113),'0','Alpha Day','0','Alpha')
INSERT INTO BoxEntries (Date,Value,Description,Empid,EmpName) Values('27-07-2017 10:24:13.000','0','Alpha Day','0','Alpha')
I have confirmed and 13 or 113 is the time of datatime i want in SQL.
The wired part is that when i try to directly add to the database the values it doesn't give me any errors.
The table:
CREATE TABLE [dbo].[BoxEntries] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Date] DATETIME NOT NULL,
[Value] MONEY NOT NULL,
[Description] VARCHAR (MAX) NOT NULL,
[EmpId] INT NOT NULL,
[EmpName] VARCHAR (MAX) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC) );
mssql format of datetime is 'YYYY-MM-DD HH:MM:SS.mmm'
https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql
so correct query for your case might be:
INSERT INTO BoxEntries ([Date],Value,Description,Empid,EmpName)
Values('2017-07-27 10:24:13.000', '0', 'Alpha Day', '0', 'Alpha');

Format Time in SQL Server?

How can I format time to only display Hours and minutes?
For example Id like LessonTime TIME(0), to show 12:00 rather than 12:00:00.
USE [Assignment]
GO
PRINT 'Creating database tables...'
CREATE TABLE [PupilDetails](
Pupil_ID INT NOT NULL,
FName VARCHAR(20),
LName VARCHAR(20),
DOB DATE,
LessonDay VARCHAR (10),
LessonTime TIME(0),
GuardianFname VARCHAR(20),
GuardianLname VARCHAR(20),
ContactNum VARCHAR(15),
AddressLine1 VARCHAR(20),
AddressLine2 VARCHAR(20),
Teacher_ID INT NOT NULL,
PRIMARY KEY (Pupil_ID),
CONSTRAINT FK_PupilDetails FOREIGN KEY (Teacher_ID)
REFERENCES Teachers(ID)
The value of time or datetime data type is not stored with format in sql server. If you want to see the time in a different format you can manipulate the way that time and datetime data types are displayed when converted to a varchar (or nvarchar,nchar,char) data type using some built in functions.
Most often with convert() styles
select convert(char(5),convert(time(0),sysdatetime()))
returns: 22:01
In sql server 2012+ you can use format()
select format(sysutcdatetime(),'HH:mm')
returns: 22:01
But format() can be slower, take a look here: format() is nice and all, but… - Aaron Bertand
SELECT LEFT(CAST(getdate() AS Time),5) AS Hours
SELECT FORMAT(SYSDATETIME(), 'h:mm tt')

Error using Liquibase on SQL Server

I'm experimenting with Liquibase, trying to get it to copy one database to another. Unfortunately, I keep getting this error:
Implicit conversion from data type varchar to varbinary is not allowed.
Use the CONVERT function to run this
query.
The SQL it's generating is here:
CREATE TABLE [dbo].[Attachment] (
[Applicantid] uniqueidentifier NOT NULL,
[Attachmentid] uniqueidentifier CONSTRAINT DF_Attachment_Attachmentid DEFAULT '(newid())' NOT NULL,
[AttachmentType] INT CONSTRAINT DF_Attachment_AttachmentType DEFAULT 0 NOT NULL,
[FileAttachment] image NOT NULL,
[FileName] ntext NOT NULL,
[FileType] nvarchar(125) NOT NULL,
[Filesize] INT NOT NULL,
[CCN] varbinary(8) CONSTRAINT DF_Attachment_CCN DEFAULT '0' NOT NULL,
[CreateDate] DATETIME CONSTRAINT DF_Attachment_CreateDate DEFAULT (getdate()) NOT NULL,
[LastUpdate] DATETIME CONSTRAINT DF_Attachment_LastUpdate DEFAULT (getdate()) NOT NULL,
CONSTRAINT [PK_Attachment] PRIMARY KEY (Attachmentid)
):
Those liquibase project guys need to learn a few things about more recent versions of SQL Server - 2005 and up:
NTEXT is long been deprecated - use NVARCHAR(MAX) instead
IMAGE is long been deprecated, too - use VARBINARY(MAX) instead
(those datatypes would be OK if you're dealing with SQL Server 2000 or earlier, however).
Plus: just from that table definition, there's no way to be able to figure out why you get this error. Is this your original (source) table, or is this what Liquibase generates as a target table?? If so: any chance you can see / trace / inspect the SQL statements used to migrate the data from the old to the new table??
Maybe there's a varchar column there that you try to convert to varbinary implicitly...