How To Create Table with Identity Column - sql

I have an existing table that I am about to blow away because I did not create it with the ID column set to be the table's Identity column.
Using SQL Server Management Studio, I scripted a "Create To..." of the existing table and got this:
CREATE TABLE [dbo].[History](
[ID] [int] NOT NULL,
[RequestID] [int] NOT NULL,
[EmployeeID] [varchar](50) NOT NULL,
[DateStamp] [datetime] NOT NULL,
CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
My question is, how would I modify this SQL so that my resulting table has the ID column set as the Identity?

CREATE TABLE [dbo].[History](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RequestID] [int] NOT NULL,
[EmployeeID] [varchar](50) NOT NULL,
[DateStamp] [datetime] NOT NULL,
CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
) ON [PRIMARY]

This has already been answered, but I think the simplest syntax is:
CREATE TABLE History (
ID int primary key IDENTITY(1,1) NOT NULL,
. . .
The more complicated constraint index is useful when you actually want to change the options.
By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.

[id] [int] IDENTITY(1,1) NOT NULL,
of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.

Unique key allows max 2 NULL values. Explaination:
create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)
insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')
select * from teppp
null string , address1
NULL,address2
NULL,address3
If you try inserting same values as below:
insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')
Every time you will get error like:
Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.

Related

How to properly create table with 3 columns as primary key?

I have been working with SQL for 3 month, I would like to know create a table with 3 columns as primary key, Any help would be great thank you.
This code below is a Scrip to Create table generated my SQL Server Management Studio of the table
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[REP]
(
[id] [UNIQUEIDENTIFIER] ROWGUIDCOL NOT NULL,
[id_client] [NCHAR](30) NULL,
[id_representant] [UNIQUEIDENTIFIER] NULL,
[date_debut] [DATE] NULL,
[date_fin] [DATE] NULL,
CONSTRAINT [PK_REP]
PRIMARY KEY CLUSTERED ([id] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[REP]
ADD CONSTRAINT [DF_REP_id] DEFAULT (NEWID()) FOR [id]
GO
First all the columns that are part of the primary key have to be not null.
then defining the key just add all columns as comma separated list.
CREATE TABLE [dbo].[REP](
[id] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[id_client] [nchar](30) NOT NULL,
[id_representant] [uniqueidentifier] NULL,
[date_debut] [date] NULL,
[date_fin] [date] NULL,
CONSTRAINT [PK_REP] PRIMARY KEY CLUSTERED
( [id] ASC,id_client ASC )
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]
In the code above I changed the column id_client to be not null and added it to the definition of the primary key ... ([id] ASC, id_client ASC).
To add more columns to a primary Key contraint you'd add the additional fields after the first field.
[id] ASC, nextfield ASC, nextfield2 asc
You can have a one composite key that comprise of more than one primary key.
CREATE TABLE xyz (
primary key (id,id_client,id_representer)
);

Insert data to column which has two relationships

So, what I want to do in here is I want to insert the data to table1 who has 'username' field, and this 'username' field has two relationships, which is go to student table and teacher table. But, when I insert the data to user table, I have a problem, and the problem caused by this 'username' field. It caused because the data of 'username' field is not the same as a unique key in student table, and when I change it and made the data same, I get an error too, but this time the data is not the same as a unique in teacher table. So, is it possible to make this 'username' field just get one of the table, like if one of student table and teacher table's data is in 'username', it still can be used. Or maybe this is wrong because of bad ERD? Here's my ERD, if you're asking it:
And well, I know this is really, really bad idea but I made the name in teacher table and student table become a unique key, because I can't create foreign key if I didn't do that. Please, I'm really thankful to your answer.
Here's the ddl for that 3 tables :
Student table :
CREATE TABLE [dbo].[student](
[studentid] [int] IDENTITY(2016000001,1) NOT NULL,
[name] [varchar](50) NOT NULL,
[address] [text] NOT NULL,
[gender] [varchar](7) NOT NULL,
[dateofbirth] [date] NOT NULL,
[nohp] [varchar](13) NOT NULL,
CONSTRAINT [PK_student] PRIMARY KEY CLUSTERED
(
[studentid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_student] UNIQUE NONCLUSTERED
(
[name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Teacher Table :
CREATE TABLE [dbo].[teacher](
[teacherid] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NOT NULL,
[gender] [varchar](7) NOT NULL,
CONSTRAINT [PK_teacher] PRIMARY KEY CLUSTERED
(
[teacherid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_teacher] UNIQUE NONCLUSTERED
(
[name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
User table:
CREATE TABLE [dbo].[user](
[userid] [int] IDENTITY(1,1) NOT NULL,
[username] [varchar](50) NOT NULL,
[password] [varchar](20) NOT NULL,
[role] [varchar](10) NOT NULL,
CONSTRAINT [PK_user] PRIMARY KEY CLUSTERED
(
[userid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[user] WITH CHECK ADD CONSTRAINT [FK_user_student] FOREIGN KEY([username])
REFERENCES [dbo].[student] ([name])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[user] CHECK CONSTRAINT [FK_user_student]
GO
ALTER TABLE [dbo].[user] WITH CHECK ADD CONSTRAINT [FK_user_teacher] FOREIGN KEY([username])
REFERENCES [dbo].[teacher] ([name])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[user] CHECK CONSTRAINT [FK_user_teacher]
GO
The main issue you faced is because your data structure was less than ideal. It did things like prevent you from changing somebody's name. I tossed together a quick example of a cleaner design. There are many assumptions here. I assumed that people have both a first and last name. I would be remiss if I didn't at least point out that assumption is not something you can always make. https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/ But for a school project it is more than sufficient. I also made the assumption that the addresses are US addresses. Again, this would not work in many real world scenarios. And the last assumption is that everybody can be either Male or Female. In the world today this is not always the case but demonstrates the technique well enough.
Here is how I would probably do this type of design. I would suggest you not just blindly copy this but use it as an idea to get your design more properly normalized.
create table Users
(
UserID int identity not null
, FirstName varchar(50) not null
, LastName varchar(50) not null
, AddressLine1 varchar(50)
, AddressLine2 varchar(50)
, City varchar(50)
, ST char(2)
, ZipCode varchar(9)
, Gender char(1)
, constraint PK_Users primary key clustered
(
UserID
)
, constraint CHK_Users_Gender
CHECK (Gender in ('M', 'F'))
, constraint CHK_Users_ZipCode
CHECK (LEN(ZipCode) in (5,9)) --This ensures you have either the 5 or 9 digiti zip code
)
create table Student
(
StudentID int identity not null
, UserID int not null
, BirthDate date
, constraint PK_Student primary key clustered
(
StudentID
)
, constraint FK_Student_Users foreign key (UserID) references Users(UserID)
)
create table Teacher
(
TeacherID int identity not null
, constraint PK_Teacher primary key clustered
(
TeacherID
)
, constraint FK_Teacher_Users foreign key (TeacherID) references Users(UserID)
)

Inserto into ( Select ) with not auto increment

Have two tables
CREATE TABLE [dbo].[TABELAA]
(
[ID] [bigint] NOT NULL,
[PodatakA] [nvarchar](50) NULL,
[PodatakB] [nvarchar](50) NULL,
CONSTRAINT [PK_TABELAA]
PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[TABELAB]
(
[PodatakX] [nvarchar](50) NULL,
[PodatakY] [nvarchar](50) NULL
) ON [PRIMARY]
GO
I need to insert value from tabelaB to tabelaA with autogenerating ID in tabelaA so I need something like this. But this would be great if there is only one row. I'm talking about thousands of rows where it should auto generate id exact like AutoIncrement (1)
Useless try where I think I should use OVER
INSERT INTO TABELAA
SELECT
(SELECT MAX(id) + 1 FROM TabelaA) AS Id, *
FROM
tabelaB
You are looking for the IDENTITY:
CREATE TABLE [dbo].[TABLAAA](
[ID] [bigint] IDENTITY(1, 1) PRIMARY KEY, -- NOT NULL is handled by PRIMARY KEY
[PodatakA] [nvarchar](50) NULL,
[PodatakB] [nvarchar](50) NULL
);
INSERT INTO TABLEAA (PodatakA, PodatakB)
SELECT PodatakA, PodatakB
FROM TABLEBB;
I agree with Rahul's comment and Gordon that if you can modify your schema it would make the most sense to add an Identity Column. However if you cannot you can still accomplish what you want using a couple of methods.
One method is get the MAX ID of TableAA and then add a ROW_NUMBER() to it like so:
INSERT INTO TableAA (ID, PodatakA, PodatakB)
SELECT
m.CurrentMaxId + ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
,b.PodatakA
,b.PodatakB
FROM
TableAB b
CROSS APPLY (
SELECT ISNULL(MAX(Id),0) as CurrentMaxId
FROM
TableAA) m
Again this would be work around the most ideal solution is to specify IDENTITY
Also this is susceptible to problems due to simultaneous writes and other scenarios in a heavy traffic DB.

How to insert IDENTITY column when creating table by this method (creating IDENTITY in table level)? [duplicate]

I have an existing table that I am about to blow away because I did not create it with the ID column set to be the table's Identity column.
Using SQL Server Management Studio, I scripted a "Create To..." of the existing table and got this:
CREATE TABLE [dbo].[History](
[ID] [int] NOT NULL,
[RequestID] [int] NOT NULL,
[EmployeeID] [varchar](50) NOT NULL,
[DateStamp] [datetime] NOT NULL,
CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
My question is, how would I modify this SQL so that my resulting table has the ID column set as the Identity?
CREATE TABLE [dbo].[History](
[ID] [int] IDENTITY(1,1) NOT NULL,
[RequestID] [int] NOT NULL,
[EmployeeID] [varchar](50) NOT NULL,
[DateStamp] [datetime] NOT NULL,
CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
) ON [PRIMARY]
This has already been answered, but I think the simplest syntax is:
CREATE TABLE History (
ID int primary key IDENTITY(1,1) NOT NULL,
. . .
The more complicated constraint index is useful when you actually want to change the options.
By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.
[id] [int] IDENTITY(1,1) NOT NULL,
of course since you're creating the table in SQL Server Management Studio you could use the table designer to set the Identity Specification.
Unique key allows max 2 NULL values. Explaination:
create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)
insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')
select * from teppp
null string , address1
NULL,address2
NULL,address3
If you try inserting same values as below:
insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')
Every time you will get error like:
Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.

Conversion failed when converting the nvarchar value 'newValue' to data type int

I'm pretty sure that I am inserting the correct data. I have drop all Indexes, Triggers, Constraint to make sure nothing is intervening my insert.
Here's the catch: the field that I'm trying to insert to previously has a datatype of int but changed to nvarchar(100) later. Does anybody know where should I look into?
This is the table structure
CREATE TABLE [dbo].[myTable.Values](
[myTableId] [bigint] NOT NULL,
[myTableCode] [nvarchar](100) NOT NULL,
[Code] [nvarchar](100) NOT NULL,
[value] [nvarchar](250) NOT NULL,
[id] [bigint] IDENTITY(1,1) NOT NULL,
[UpdateById] [bigint] NOT NULL,
[UpdateDate] [datetime] NOT NULL,
CONSTRAINT [PK_myTable.Values] PRIMARY KEY CLUSTERED
(
[myTableCode] ASC,
[Code] ASC,
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, `ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]`
) ON [PRIMARY]
and this is the script for insert
INSERT INTO [dbo].[myTable.Values] (
[myTableId]
,[myTableCode]
,[Code]
,[value]
,[UpdateById]
,[UpdateDate]
)
VALUES (
581
,'myParentTableCODE'
,'myTableNewCode'
,'myTableNewCode'
,5197
,getdate()
)
Thanks for looking into this, I have found out one of our View is using "WITH SCHEMABINDING" clause. And that view is Casting the field "Code" as int. Here is the view.
CREATE VIEW [dbo].[vSomeView] WITH SCHEMABINDING
AS
SELECT
id,
CAST(Code AS INT) AS [Code],
myTableCode
FROM dbo.[myTable.Values]
WHERE myTableCode LIKE '%ABC'
AND ISNUMERIC(Code) = 1
it seems yourinsertion code is not complete, you should to add another field and assign value to it,the field is IsDefaultObsolete, then try this code for insert :
INSERT INTO [dbo].[myTable.Values] (
[myTableId]
,[myTableCode]
,[Code]
,[value]
,[IsDefaultObsolete]
,[UpdateById]
,[UpdateDate]
)
VALUES (
581
,'myParentTableCODE'
,'myTableNewCode'
,'myTableNewCode'
0,--THIS MAY BE 0 OR 1 DEPENDING YOU
,5197
,getdate()
)