Format Time in SQL Server? - sql

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')

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'

Missing right parenthesis Oracle Issue

I 'm using Oracle Application Express Edition 4.0.2.00.09
While creating the table I'm getting error "ORA-00907: missing right parenthesis", I have checked previously asked question on this however could not make it through.
Create table NewOne (
PersonId Int(10),
Hire_Date varchar(255),
Tenure number(255),
Review varchar(255),
Next_Day varchar(255),
Last_day varchar(255)
)
Make the changes below
Change int to number
Change number(255) to number(38) , as 38 is the max allowed for number
It should work fine.
Check out the db fiddle link - https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=d1fecc3e55708115d2326fdeec34243d
You can't specify a length for the INT subtype, it is what it is. You should use the NUMBER type instead.
Once you fix that you'll find that your tenure column is specified with 255 digits, I don't think that's close to reality and will also error.
You should be using VARCHAR2 not VARCHAR on Oracle.
int is a perfectly acceptable Oracle type. However, int(10) is not. Number itself is limited to a max of 38. And Oracle recommend varchar2() instead of varchar(). So I would recommend:
Create table NewOne (
PersonId Int,
Hire_Date varchar2(255),
Tenure number,
Review varchar2(255),
Next_Day varchar2(255),
Last_day varchar2(255)
);
Here is a db<>fiddle

Incorrect syntax around datetime2

The following CREATE statement is meant for SQL Server:
CREATE TABLE tclientlink
(
link_id INT,
ext_client_id VARCHAR(255),
goald_address_id VARCHAR(255),
goald_client_id VARCHAR(255),
instance_id VARCHAR(255),
source_id VARCHAR(255),
timestamp DATETIME2
);
The INSERT statement
INSERT INTO TCLIENTLINK(link_id, ext_client_id, goald_address_id, goald_client_id, instance_id, source_id, timestamp)
VALUES (13582, "0000059811", "3037260", "0000059811", "1", "1", 2018-08-22 15:13:34);
But when I try to validate this using an online tool, I get the following error message:
You have an error in your SQL syntax; it seems the error is around: 'datetime2 )'
What change do I need to make to my DDL above?
double quote indicate column name, as a result if you use double quote sql server engine will search that column name , so in case of value you have to use single quote and also for datetime column value should be quoted. so working query is below
CREATE TABLE tclientlink
(
link_id INT,
ext_client_id VARCHAR(255),
goald_address_id VARCHAR(255),
goald_client_id VARCHAR(255),
instance_id VARCHAR(255),
source_id VARCHAR(255),
timestamp DATETIME2
);
INSERT INTO TCLIENTLINK(link_id, ext_client_id, goald_address_id, goald_client_id, instance_id, source_id, timestamp)
VALUES (13582, '0000059811', '3037260', '0000059811', '1', '1', '2018-08-22 15:13:34');
Your insert statement might be this.
use ' instead of " for string value, and the datetime2 need to use ' contain it.
INSERT INTO TCLIENTLINK(link_id, ext_client_id, goald_address_id, goald_client_id, instance_id, source_id, timestamp) VALUES(13582,'0000059811','3037260','0000059811','1','1', '2018-08-22 15:13:34');
sqlfiddle

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 Create table in database ssms

I would like to create a database with a couple tables in it. I am using SSMS and it is easy enough to accomplish said task by right-click creating, but I would like to use query/command line (not sure how to phrase that).
Create a database and table
CREATE DATABASE test_employees;
CREATE TABLE dbo.EmployeesBasicInfo
(
MyKeyField VarChar(8) PRIMARY KEY,
FirstName VarChar(30) NOT NULL,
LastName VarChar(50) NOT NULL,
DateStarted DateTime NOT NULL,
Age Int NOT NULL,
ModifiedDate DateTime NULL
);
But I have no idea where the table goes or how to move/link it to database test_employees.
Also, if you feel ambition in answering my question then the next step is to auto-generate data for all fields. Any links you could provide would be helpful. And, if anything I'm doing is not best-practice please let me know - I'm just getting into SQL.
After you've created the database you need to
Use test_employees
Go
This sets your current working database for subsequent statements.
Alternatively you can qualify your create table with the database name
Create Table test_employees.dbo.EmployeesBasicInfo (
MyKeyField varchar(8) primary key,
FirstName varchar(30) not null,
LastName varchar(50) not null,
DateStarted DateTime not null,
Age int not null,
ModifiedDate datetime null
);
You've probably created this table in your default database, which may well be master.
Also for any recent version of SQL Server, consider using datetime2 instead of datetime (or date if you don't need the time component). It's better in all respects.
Here is some code to create a table 1st and then you can add some test data into it to practice with .......
TO CREATE A TABLE :
Create Table dbo.BasicInfo (
MyKeyField INT primary key IDENTITY(1,1),
FirstName varchar(30) not null,
LastName varchar(50) not null,
DateStarted DateTime not null,
Age int not null,
ModifiedDate datetime null
)
GO
TO ADD PRACTICE DATA:
DECLARE #Value INT = 1
WHILE #Value <= 100
BEGIN
INSERT INTO dbo.BasicInfo (FirstName, LastName, DateStarted, Age, ModifiedDate)
VALUES ('First_Name_' + CAST(#Value AS VARCHAR), 'Last_Name_'+ CAST(#Value AS VARCHAR), DATEADD(DAY, -CONVERT(INT, (5000+1)*RAND()), GETDATE()),
18 + CONVERT(INT, (30-10+1)*RAND()), DATEADD(DAY, 10 + (30-10)*RAND() ,DATEADD(DAY, -CONVERT(INT, (5000+1)*RAND()), GETDATE())))
SET #Value = #Value + 1
END
if you want to add more then 100 rows in your table just replace the number or rows you wish to add to your table with 100 in this code