SQL identity with character autogenerated - sql

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
)

Related

SQL table creation issue with , similar to, relation foreign key with primary key

can anyone help me with this sql statment
Create table doctor(
doctorId char(3),
doctorName varchar(20),
primary key (doctorId)
);
create table patient (
patient_id char(4) not null check (patient_id LIKE 'P[0-9][0-9][0-9]'),
doctorId char(3),
patientName varchar(60) not null,
dateOfBirth date not null,
gender char(1),
height decimal(4, 1) check (height > 0),
weight decimal(4, 1) check(weight > 0),
primary key (patient_id) FOREIGN KEY doctorId REFERENCES doctor(doctorId)
);
why 2nd table not created
put these below code instead of your own code:
Create table doctor(
doctorId char(3),
doctorName varchar(20),
primary key (doctorId)
);
create table patient (
patient_id char(4) not null check (patient_id LIKE 'P[0-9][0-9][0-9]'),
doctorId char(3),
patientName varchar(60) not null,
dateOfBirth date not null,
gender char(1),
height decimal(4, 1) check (height > 0),
weight decimal(4, 1) check(weight > 0),
primary key (patient_id) FOREIGN KEY doctorId REFERENCES doctor(doctorId)
);
Thats because you are missing a ,
create table patient (
patient_id char(4) not null check (patient_id LIKE 'P[0-9][0-9][0-9]'),
doctorId char(3),
patientName varchar(60) not null,
dateOfBirth date not null,
gender char(1),
height decimal(4, 1) check (height > 0),
weight decimal(4, 1) check(weight > 0),
primary key (patient_id) ,
FOREIGN KEY (doctorId) REFERENCES doctor(doctorId)
);
It should be like that.
Create table doctor(
doctorId Int Identity(1,1), --It's 'Primary Key' so it should be Int or Guid
doctorName varchar(20),
CONSTRAINT pk_doctorId PRIMARY KEY (doctorId) --It's better!
);
Create table patient (
patient_id Int IDENTITY(1,1), --It's 'Primary Key' so it should be Int or Guid
doctorId Int NOT NULL, --Every patient has a doctor, so it should be 'Not Null'
patientName varchar(60) not null,
dateOfBirth date not null,
gender char(1),
height decimal(4,1), -- I didnt see check operator, you should check > 0 in code.
weight decimal(4,1),
CONSTRAINT pk_patient_id PRIMARY KEY (patient_id),
CONSTRAINT fk_doctorId FOREIGN KEY (doctorId) REFERENCES doctor(doctorId)
);

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 How to convert this to a SubQuery?

Learning, be kind.
I am trying to understand how this works and I have done several successful conversions, but this one I am stumped on.
How do I take this code and convert it to a subquery? I'm a little lost.
SELECT o.FirstName + ' ' + o.LastName AS Driver, COUNT(DISTINCT s.vehicleID) NoOfBusesUsed
FROM Operators AS o, Runs AS r, Schedules AS s JOIN Trips AS t
ON s.scheduleID = t.scheduleID
WHERE r.BidDate BETWEEN '09/01/2004' AND '09/30/2004'
GROUP BY o.FirstName + ' ' + o.LastName
HAVING COUNT(s.vehicleID) > 1
Here is how my tables are setup. If more info is needed, I can post.
CREATE TABLE Operators
(
SeniorityNumber char(4) NOT NULL
CONSTRAINT ck_Operators_Seniority
CHECK (SeniorityNumber LIKE '[0-9][0-9][0-9][0-9]'),
FirstName varchar(25) NOT NULL,
LastName varchar(35) NOT NULL,
HireDate smalldatetime
CONSTRAINT ck_Operators_HireDate CHECK (HireDate <=Getdate())
)
CREATE TABLE Trips
(
RouteNumber varchar(4) NOT NULL,
StartLocation varchar(50) NOT NULL,
StartTime time NOT NULL,
EndLocation varchar(50) NOT NULL,
EndTime time NOT NULL,
EffectiveDate smalldatetime NOT NULL
CHECK (EffectiveDate >= cast('1/1/2000' as smalldatetime)),
CONSTRAINT ck_Trips_StartEnd CHECK (EndTime > StartTime)
)
CREATE TABLE Vehicles
(
Manufacturer varchar(50)
DEFAULT 'Gillig',
Model varchar(50),
ModelYear int
DEFAULT DatePart(yyyy,GetDate())
CHECK (ModelYear <= DatePart(yyyy,GetDate())),
PurchaseDate smalldatetime
)
GO
ALTER TABLE operators
ADD OperatorID int IDENTITY --Primary Key
GO
ALTER TABLE Operators
ADD CONSTRAINT pkOperators Primary key (OperatorID)
ALTER TABLE Vehicles
ADD VehicleID int IDENTITY Primary Key
ALTER TABLE Trips
ADD TripID int IDENTITY Primary key
GO
CREATE TABLE Runs
(
RunID int IDENTITY NOT NULL Primary Key,
OperatorID int NOT NULL REFERENCES Operators,
BidDate date NOT NULL
CONSTRAINT ckRunBidDate CHECK
(biddate <= dateadd(mm,6,getdate())) --getdate() + 180
)
GO
CREATE TABLE Schedules
(
ScheduleID int IDENTITY Primary Key,
RunID int NOT NULL,
VehicleID int NOT NULL,
CONSTRAINT fk_Schedules_Runs FOREIGN KEY (RunID)
REFERENCES Runs(RunID),
CONSTRAINT fk_Schedules_Vehicles FOREIGN KEY (VehicleID)
REFERENCES Vehicles
)
ALTER TABLE Trips
ADD ScheduleID int NULL REFERENCES Schedules
When you want to use a query as a sub-query you can use WITH statement or a derived table like:
With:
;WITH subQuery AS (
/* Your query here */
)
SELECT *
FROM subQuery
Derived table
SELECT *
FROM (
/* your query here */
) As subQuery
I think you should use a query like this:
SELECT
o.FirstName + ' ' + o.LastName AS Driver,
DT.cnt AS NoOfBusesUsed
FROM
Operators AS o
JOIN
(SELECT
r.OperatorID,
COUNT(DISTINCT s.VehicleID) AS cnt
FROM
Schedules s
JOIN
Runs r ON s.RunID = r.RunID
) AS DT
ON DT.OperatorID = o.OperatorID
WHERE
ISNULL(DT.cnt, 0) > 1

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

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....