Create Table column date format dd-mm-yyyy SQL Server - sql

I have a table where there are 3 columns to store different dates for different purposes. I would like to store the date in dd-mm-yyyy. Below is the code:
create table PoojaDetails
(
PoojaDetailsID int identity constraint pk_PoojaDetailsID Primary Key,
ReceiptNo AS 'PB' + '/' + cast(datepart(yy,getdate()) as varchar(25)) + '/' + RIGHT('000000000' + CAST(PoojaDetailsID AS VARCHAR(10)), 9) ,
ReceiptDate date not null constraint df_ReceiptDate default convert(date,getdate()),
FirstName varchar(100) not null,
LastName varchar(100) not null,
TelNo bigint,
Star char(50) not null,
Rasi char(50) not null,
Gothram char(100) not null,
PoojaDietyMasterID int not null,
Schedule char(1) not null constraint df_schedule default 'F',
PoojaDate date not null constraint df_pdate default convert(date, '29122013'),
PayMode bit not null,
isDonate bit not null constraint df_isDonate default 1,
DonateAmount float(10),
ChequeNo int,
BankName varchar(255),
ChequeDated date,
UserID int,
SupID int,
ChangeDate date,
Remarks varchar(255),
isPrint char(1) constraint df_isPrint default 'N',
isDeleted bit not null constraint df_isDeleted default 1
)
I would like to have the format for:
ReceiptDate
PoojaDate
ChequeDate
ChangeDate
Thanks :)

Your best bet will be to store the date (if you are using SQL 2008, you should use the DATE datatype) in the universal format of yyyymmdd in the database and then use
CONVERT(Date,YourColumn,105)
when reading the data, to get it in the format you desire.

CONVERT(VARCHAR(10), ReceiptDate, 105) AS [DD-MM-YYYY]
CONVERT(VARCHAR(10), PoojaDate, 105) AS [DD-MM-YYYY]
CONVERT(VARCHAR(10), ChequeDate , 105) AS [DD-MM-YYYY]
use this link for referrence....

Related

I am trying to create a table in SQL and keep getting an error

I'm using Teradata SQL assistant to create a table. The code I am using is as follows:
CREATE TABLE calendar
(
CalendarKey INT NOT NULL,
FullDate DATE NOT NULL,
DayOfWeek VARCHAR(20) NOT NULL,
DayOfMonth INT NOT NULL,
Month VARCHAR(20) NOT NULL,
Qtr VARCHAR(2) NOT NULL,
Year VARCHAR(4) NOT NULL
PRIMARY KEY (CalendarKey)
);
I get this error when I try to execute the command:
[Teradata Database] [3707] Syntax error, expected something like a 'CHECK' keyword between ',' and the 'Month' keyword.
Does anyone know what the issue is?
As the error implies month (and year, too) is a reserved keyword in Teradata, which can't be used as column name.
You might double quote it (but then you have to double quote it in every query, too) or you change the name. There's another issue, a missing comma before the primary key constraint:
CREATE TABLE calendar
(
CalendarKey INT NOT NULL,
FullDate DATE NOT NULL,
DayOfWeek VARCHAR(20) NOT NULL,
DayOfMonth INT NOT NULL,
"Month" VARCHAR(20) NOT NULL,
Qtr VARCHAR(2) NOT NULL,
"Year" VARCHAR(4) NOT NULL,
PRIMARY KEY (CalendarKey)
);
Try this way
CREATE TABLE calendar (
CalendarKey INT NOT NULL,
FullDate DATE NOT NULL,
DayOfWeek VARCHAR(20) NOT NULL,
DayOfMonth INT NOT NULL,
Month VARCHAR(20) NOT NULL,
Qtr VARCHAR(2) NOT NULL,
Year VARCHAR(4) NOT NULL
)
and
ALTER TABLE `calendar` ADD PRIMARY KEY (`CalendarKey`);
Try this, to have a table with PK as part of Table Definition
CREATE TABLE calendar
(
CalendarKey INT PRIMARY KEY NOT NULL,
FullDate DATE NOT NULL,
[DayOfWeek] VARCHAR(20) NOT NULL,
[DayOfMonth] INT NOT NULL,
[Month] VARCHAR(20) NOT NULL,
Qtr VARCHAR(2) NOT NULL,
[Year] VARCHAR(4) NOT NULL
);
Or this to have Primary Key PK with an Identity [auto counter]
CREATE TABLE calendar
(
CalendarKey INT PRIMARY KEY Identity(1,1) NOT NULL,
FullDate DATE NOT NULL,
[DayOfWeek] VARCHAR(20) NOT NULL,
[DayOfMonth] INT NOT NULL,
[Month] VARCHAR(20) NOT NULL,
Qtr VARCHAR(2) NOT NULL,
[Year] VARCHAR(4) NOT NULL
);
- Note, it's recommended to use prackets [] if the col name is a reserved key-word , like [year]

DATETIME gives date without time in SQL Server

I have a SQL query which should convert a datetime. I have tried it in different ways but in every way something goes wrong.
INSERT INTO SETTLEMENT_WIN (COUNTRY,
COMMODITY,
MARKET_PLACE,
START_TIME,
END_TIME)
VALUES ('BE', 'EL', NULL, CONVERT(datetime, '2015-12-14 15:45', 'YYYY-MM-DD HH24:MI'), CONVERT(datetime, '2015-12-14 16:00', 'YYYY-MM-DD HH24:MI'));
gives the error:
Msg 8116, Level 16, State 1, Line 1 Argument data type varchar is
invalid for argument 3 of convert function.
INSERT INTO SETTLEMENT_WIN (COUNTRY,
COMMODITY,
MARKET_PLACE,
START_TIME,
END_TIME)
VALUES ('BE', 'EL', NULL, CONVERT(datetime, '2008-12-14 15:45', 120), CONVERT(datetime, '2015-12-14 16:00', 120));
Inserts the row but in START_TIME and END_TIME there is only the date but not the time
Then I tried to only insert the time but even then only the date was inserted (I am not allowed to change the date format).
Declare #Date1 datetime ='2008-12-14 15:45';
Declare #Date2 datetime ='2015-12-14 16:00';
INSERT INTO SETTLEMENT_WIN (COUNTRY,
COMMODITY,
MARKET_PLACE,
START_TIME,
END_TIME)
VALUES ('BE', 'EL', NULL, CONVERT(datetime, #Date1, 108), CONVERT(datetime, #Date2, 108));
What am I doing wrong? I am using Microsoft SQL Server Management Studio 17.
The CREATE statement for my table is:
CREATE TABLE [SETTLEMENT_WIN] ([SW_ID] [numeric](18, 0) IDENTITY(1, 1) NOT NULL,
[COUNTRY] [varchar](32) NOT NULL,
[COMMODITY] [varchar](32) NOT NULL,
[MARKET_PLACE] [varchar](32),
[START_TIME] [date] NOT NULL,
[END_TIME] [date] NOT NULL,
CONSTRAINT [SW_PK]
PRIMARY KEY ([SW_ID]));
Exactly as I suspected:
[START_TIME] [date] NOT NULL,
[END_TIME] [date] NOT NULL,
If you provide a datetime value to a date datatype the time part of the value will be lost. Try:
DECLARE #d date;
SET #d = '2018-08-02T11:15:59.462'
SELECT #d;
Note it returns 2018-08-02. A date is just that, a date. A datetime, datetime2 or datetimeoffset needs to be used to store a date and time. You'll need to fix your table to resolve this:
ALTER TABLE dbo.SETTLEMENT_WIN ALTER COLUMN [START_TIME] datetime2(0) NOT NULL;
ALTER TABLE dbo.SETTLEMENT_WIN ALTER COLUMN [END_TIME] datetime2(0) NOT NULL;
Then you can insert a date and time value in your table.
#SilverFullbuster, you will need the datatype column in START_TIME and END_TIME changed from date to [datetime].
from:
CREATE TABLE [SETTLEMENT_WIN] ([SW_ID] [numeric](18, 0) IDENTITY(1, 1) NOT NULL,
[COUNTRY] [varchar](32) NOT NULL,
[COMMODITY] [varchar](32) NOT NULL,
[MARKET_PLACE] [varchar](32),
[START_TIME] [date] NOT NULL,
[END_TIME] [date] NOT NULL,
CONSTRAINT [SW_PK]
PRIMARY KEY ([SW_ID]));
to
CREATE TABLE [SETTLEMENT_WIN] ([SW_ID] [numeric](18, 0) IDENTITY(1, 1) NOT NULL,
[COUNTRY] [varchar](32) NOT NULL,
[COMMODITY] [varchar](32) NOT NULL,
[MARKET_PLACE] [varchar](32),
[START_TIME] [datetime] NOT NULL,
[END_TIME] [datetime] NOT NULL,
CONSTRAINT [SW_PK]
PRIMARY KEY ([SW_ID]));
and you can pull the starttime/endtime by extracting from the datetime column like this:
SELECT
SW_ID,
COUNTRY,
COMMODITY,
MARKET_PLACE,
START_TIME=convert(varchar(8), START_TIME, 108),
END_TIME=convert(varchar(8), END_TIME, 108)
FROM
SETTLEMENT_WIN
and results will be like this:

Persisted column throwing non-deterministic error using convert

Using SQL Server 2016 and I'm running into a little bit of a problem.
Here's my use case that is causing issues for me...
create table dbo.Example (
Id int identity (1, 1) not null,
[Name] nvarchar(100) not null,
Email nvarchar(255) not null,
DOB datetime2(7) not null,
RowHash as convert(nvarchar(66), hashbytes('SHA1', coalesce(
convert(nvarchar(max), [Name]),
convert(nvarchar(max), Email),
convert(nvarchar(max), DOB)
))) persisted
constraint [PK_Example] primary key clustered (Id asc)
);
drop table dbo.Example;
The message I'm getting is:
Msg 4936, Level 16, State 1, Line 1
Computed column 'RowHash' in table 'Example' cannot be persisted because the column is non-deterministic.
When I set the column to not be persisted, the data type is interpreted correctly as nvarchar(66) however I would like to have it persisted. The issue seems to be related to the datetime2 column however I have a mixture of data types on the table.
So the goals are to use a persisted hashbytes column to hold a hash of all the values in my table.
Any ideas?
Thx!
Why coalesce() and not concat()?
Example
create table dbo.Example (
Id int identity (1, 1) not null,
[Name] nvarchar(100) not null,
Email nvarchar(255) not null,
DOB datetime2(7) not null,
RowHash as convert(nvarchar(66), hashbytes('SHA1', concat(
[Name],
Email,
DOB
))) persisted
constraint [PK_Example] primary key clustered (Id asc)
);
Select * from [dbo].[Example]
--drop table dbo.Example;
Results
You can fix this by specifying a format for the date conversion:
create table dbo.Example (
Id int identity (1, 1) not null,
[Name] nvarchar(100) not null,
Email nvarchar(255) not null,
DOB date not null, -- I figure date is good enough
RowHash as convert(nvarchar(66), hashbytes('SHA1', concat(
convert(nvarchar(max), [Name]),
convert(nvarchar(max), Email),
convert(nvarchar(max), DOB, 121)
))) persisted
constraint [PK_Example] primary key clustered (Id asc)
);
The problem is that the default date-to-string conversion depends on system parameters, so it is not deterministic. For a persisted column, all components need to be deterministic.
I would love to say that the documentation covers this exotic point in well-balanced detail. Not quite. You can get the idea from this documentation. Just be forgiving -- it also applies to date, datetime2 and other data types.
Here's the final result which is a combo of both answers above. Thx very much for the help.
create table dbo.Example (
Id int identity (1, 1) not null,
[Name] nvarchar(100) not null,
Email nvarchar(255) not null,
DOB datetime2(7) null,
RowHash as convert(nvarchar(66), hashbytes('SHA1', concat(
convert(nvarchar(max), [Name]),
convert(nvarchar(max), Email),
convert(nvarchar(max), DOB, 121)
))) persisted
constraint [PK_Example] primary key clustered (Id asc)
);
drop table dbo.Example;

Computed persisted column does not pick index and shows conversion warning in SQL Server 2016 sp1-cu4

I created PK based on identity column a computed persisted column as
('P'+ RIGHT('000000000' + CONVERT([VARCHAR](8), [ID], (0)), (7))) PERSISTED
I created both tables, in the same way, a persisted columns. When I tried to join both persisted columns on inner join, it does not pick the index and warning is being shown
Type conversion expression convert(varchar(8), id, 0) may effect cardinality estimate in version Microsoft SQL Server 2016 -sp1cu4
Table #1:
create table dbo.master_designation
(
id int identity(1,1) not null,
dept_code varchar(8) not null,
user_type_code varchar(8) not null,
desig_code as ('P'+ RIGHT('0000000' + CONVERT([VARCHAR](8), [ID], (0)), (7))) PERSISTED,
name varchar(30) not null,
shortname varchar(30) not null
) on primary
Create index:
create nonclustered index idx2
on master_designation (desig_code);
Table #2:
create table dbo.mapping_employee_designation
(
id int identity(1,1) not null,
emp_code varchar(8) not null,
dept_code varchar(8) not null,
desig_code as ('P'+ RIGHT('0000000' + CONVERT([VARCHAR](8), [ID], (0)), (7))) PERSISTED,
location_code varchar(5) null,
report_to varchar(8) null,
active bit not null
) on primary
Create index
create nonclustered index idx1
on mapping_employee_designation (desig_code);

SQL identity with character autogenerated

I have the below table: Using SQL Server
create table PoojaDetails
(
PoojaDetailsID int identity constraint pk_PoojaDetailsID Primary Key,
ReceiptNo AS 'PB' + '/' + datepart(yy,getdate()) + '/' + RIGHT('000000' + CAST(PoojaDetailsID AS VARCHAR(10)), 6) PERSISTED,
ReceiptDate datetime not null constraint df_ReceiptDate default getdate(),
FirstName varchar(100) not null,
LastName varchar(100) not null,
TelNo bigint
)
When i execute the query: Computed column 'ReceiptNo' in table 'PoojaDetails' cannot be persisted because the column is non-deterministic.
I would like to have the ReceiptNo as : PB/year/no
for e.g; PB/13/213433
Any ideas??? Thanks for your time
Please Try it,
create table PoojaDetails
(
PoojaDetailsID int identity constraint pk_PoojaDetailsID Primary Key,
ReceiptNo AS 'PB' + '/' + cast(datepart(yy,getdate()) as varchar(25)) + '/' + RIGHT('000000' + CAST(PoojaDetailsID AS VARCHAR(10)), 6) ,
ReceiptDate datetime not null constraint df_ReceiptDate default getdate(),
FirstName varchar(100) not null,
LastName varchar(100) not null,
TelNo bigint
)
If you can rely on ReceiptDate always being populated by its default constraint and never changing, then you can use it instead of getdate() in your computed column:
create table PoojaDetails
(
PoojaDetailsID int identity constraint pk_PoojaDetailsID Primary Key,
ReceiptNo AS 'PB' + '/' + CONVERT(varchar(5),datepart(yy,ReceiptDate)) + '/' + RIGHT('000000' + CAST(PoojaDetailsID AS VARCHAR(10)), 6) PERSISTED,
ReceiptDate datetime not null constraint df_ReceiptDate default getdate(),
FirstName varchar(100) not null,
LastName varchar(100) not null,
TelNo bigint
)