I have a table: Sales_Table with columns:
ProductKey Int not null,
UnitPrice decimal 18,2,
SalesAmount decimal 18,2
I am trying to add a primary key to the ProductKey column using alter table
ALTER TABLE SALES_TABLE
ADD PRIMARY KEY (ProductKey)
after I run the code and I get the following error:
Msg 1505, Level 16, State 1, Line 9 The CREATE UNIQUE INDEX statement
terminated because a duplicate key was found for the object name
'dbo.Sales_Table' and the index name 'PK__Sales_Ta__A15E99B36F3FE24F'.
The duplicate key value is (604).
What can I do to overcome this issue? Thanks in Advance.
Try this
IF NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='Product')
BEGIN
CREATE TABLE [dbo].[Product](
[ProductKey] [int] NOT NULL,
[UnitPrice] [decimal](18, 2) NULL,
[SalesAmount] [decimal](18, 2) NULL,
) ON [PRIMARY]
END
IF NOT EXISTS(SELECT 1 FROM sys.indexes WHERE name='Pk_Product')
BEGIN
ALTER TABLE [dbo].[Product] ADD CONSTRAINT [Pk_Product] PRIMARY KEY CLUSTERED
(
[ProductKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END
Related
This question already has answers here:
How to insert a row into another table using last inserted ID?
(4 answers)
Closed 4 months ago.
I have a table 1 with an auto-generated primary key in SQL Server. I have a second table 2 where the auto-generated value from table 1 is a foreign key in table 2.
How can I write a query where I can INSERT into table 2, including the auto-generated value from table 1.
Preferably this would also work in a stored procedure.
Generate scripts:
CREATE TABLE [dbo].[POSTADRESSE](
[AdresseID] [int] IDENTITY(1,1) NOT NULL,
[GateNavn] [varchar](50) NULL,
[GateNR] [varchar](10) NULL,
[PostNR] [int] NULL,
[PostSted] [varchar](30) NULL,
CONSTRAINT [XPKPOSTADRESSE] PRIMARY KEY CLUSTERED
(
[AdresseID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[KUNDE](
[TelefonNR] [varchar](15) NOT NULL,
[AdresseID] [int] NOT NULL,
[Epost] [varchar](320) NULL,
[Fornavn] [varchar](100) NULL,
[Etternavn] [varchar](100) NULL,
[Passord] [varchar](69) NULL,
CONSTRAINT [XPKKUNDE] PRIMARY KEY CLUSTERED
(
[TelefonNR] ASC,
[AdresseID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
This is what I've tried:
INSERT INTO POSTADRESSE(GateNavn, GateNR, PostNR, PostSted)
VALUES ('Storgt', 3, 3901, 'Porsgrunn')
INSERT INTO KUNDE(TelefonNR, AdresseID, Epost, Fornavn, Etternavn, Passord)
VALUES (
47843329,
(SELECT POSTADRESSE.AdresseID FROM POSTADRESSE WHERE POSTADRESSE.GateNavn = 'Storgt'),
'hej#hotmail.se',
'Anton',
'Johanson',
'123abc'
);
Hi #VaBraAnton see this answer will help.
Declare #Identity as int
INSERT INTO POSTADRESSE(GateNavn, GateNR, PostNR, PostSted)
VALUES ('Storgt', 3, 3901, 'Porsgrunn')
Select #Identity=SCOPE_IDENTITY();
INSERT INTO KUNDE(TelefonNR, AdresseID, Epost, Fornavn, Etternavn, Passord)
VALUES (
47843329,
#Identity,
'hej#hotmail.se',
'Anton',
'Johanson',
'123abc'
);
see screen shot
I have 3 tables
crm.Documents
crm.GroupDocuments
schedular.Groups
Documents table looks like
Id Name
-----------
1 Test
GroupDocuments table looks like
Id | GroupId | DocumentId
---+---------+------------
1 | 1 | 1
2 | 2 | 1
Group table looks like
Id | Name
---+--------
1 | Sales
2 | Service
3 | Techs
The code to create these tables is :
CREATE TABLE [crm].[Documents]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](100) NOT NULL,
[FileType] [int] NOT NULL,
[Bytes] [varbinary](max) NOT NULL,
[IsShared] [bit] NOT NULL,
[UploadDate] [datetime2](7) NOT NULL,
[LastSaveDate] [datetime2](7) NOT NULL,
CONSTRAINT [PK_Documents]
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] TEXTIMAGE_ON [PRIMARY]
CREATE TABLE [scheduler].[Groups]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
CONSTRAINT [PK_Groups]
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]
CREATE TABLE [crm].[GroupDocuments]
(
[GroupId] [int] NOT NULL,
[DocumentId] [int] NOT NULL,
CONSTRAINT [PK_GroupDocuments]
PRIMARY KEY CLUSTERED ([GroupId] ASC, [DocumentId] 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 [crm].[GroupDocuments] WITH CHECK
ADD CONSTRAINT [FK_GroupDocuments_Documents_GroupId]
FOREIGN KEY([GroupId]) REFERENCES [crm].[Documents] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [crm].[GroupDocuments] CHECK CONSTRAINT [FK_GroupDocuments_Documents_GroupId]
GO
ALTER TABLE [crm].[GroupDocuments] WITH CHECK
ADD CONSTRAINT [FK_GroupDocuments_Groups_DocumentId]
FOREIGN KEY([DocumentId]) REFERENCES [scheduler].[Groups] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [crm].[GroupDocuments] CHECK CONSTRAINT [FK_GroupDocuments_Groups_DocumentId]
GO
When I run
INSERT INTO crm.GroupDocuments (GroupId, DocumentId)
VALUES (3, 1)
I get this error:
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_GroupDocuments_Documents_GroupId".
The conflict occurred in database "Scheduler", table "crm.Documents",
column 'Id'.
There is an Id 3 on the group table and an Id 1 on the documents table. Can someone please explain why this error would occur?
You have inverted your FOREIGN KEY references....
ALTER TABLE [crm].[GroupDocuments]
ADD CONSTRAINT [FK_GroupDocuments_Documents_GroupId]
FOREIGN KEY([**GroupId**]) REFERENCES [crm].[**Documents**] ([Id])
You've criss-crossed the referenced columns in the definition of your foreign key constraints .... your DocumentID references Groups.Id, while GroupId references Documents.Id....
Change your FK statements to:
-- "GroupId" should reference "Groups.Id" (not "Documents.Id") .....
ALTER TABLE [crm].[GroupDocuments] WITH CHECK
ADD CONSTRAINT [FK_GroupDocuments_GroupId]
FOREIGN KEY([GroupId]) REFERENCES [scheduler].[Groups]([Id])
ON DELETE CASCADE
GO
-- and "DocumentId" should reference "Documents.Id" (not "Groups.Id")
ALTER TABLE [crm].[GroupDocuments] WITH CHECK
ADD CONSTRAINT [FK_GroupDocuments_DocumentId]
FOREIGN KEY([DocumentId]) REFERENCES [crm].[Documents]([Id])
ON DELETE CASCADE
GO
I am getting below error and if I don't use computed column then it works fine .
Msg 213, Level 16, State 1, Procedure test1tri, Line 3 [Batch Start Line 24]
Column name or number of supplied values does not match table definition.
this is sample I am using:
drop table test2
CREATE TABLE test2 ([ID] [INT], [NAME] [VARCHAR](100), [ADDRESS] [VARCHAR](100)
CONSTRAINT [PK_test2] 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]
ALTER TABLE test2
ADD full_name AS (name + ' ' + address) persisted;
drop table test3
CREATE TABLE test3 ([$delete] [bit] NULL,[ID] [INT], [NAME] [VARCHAR](100), [ADDRESS] [VARCHAR](100)
CONSTRAINT [PK_test3] UNIQUE 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 test3
ADD full_name AS (name + ' ' + address) persisted;
CREATE TRIGGER [test1tri] ON [test2]
INSTEAD OF INSERT AS
INSERT INTO [test3] SELECT 0,* FROM inserted
GO
While you want to insert new record to table you should not provide value for the computed column. So you can rewrite your trigger as below:
CREATE TRIGGER [test1tri] ON [test2]
INSTEAD OF INSERT AS
INSERT INTO [test3] SELECT 0,
Inserted.ID,
Inserted.NAME,
Inserted.ADDRESS FROM inserted
GO
I am a beginner in SQL,
I have a table with GroupRole column and Age column.
CREATE TABLE [Persons](
[PersonID] [int] IDENTITY(1,1) NOT NULL,
[FullName] [varchar](70) NULL,
[Age] [int] NULL,
[GroupRole ] [varchar](30) NULL
CONSTRAINT [PK_Persons] PRIMARY KEY CLUSTERED
(
[PersonID] 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
I want to limit the value range that can be placed in an age column lower 30
and GroupRole column equal 'Admin'.
I do not want to do this in the c# code.
How can I do it?
this have easy way:
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=30 AND GroupRole ='Admin');
You need to use Check Constraints. They are part of your table's metadata and define conditions to be checked every time, when the data is modified or inserted in the table. If these conditions are not met, the DML operation will fail with an error.
You need to modify your CREATE TABLE statement as follows:
CREATE TABLE [Persons](
[PersonID] [int] IDENTITY(1,1) NOT NULL,
[FullName] [varchar](70) NULL,
[Age] [int] NULL CONSTRAINT CHK_Age CHECK ([Age] < 30),
[GroupRole] [varchar](30) NULL CONSTRAINT CHK_GroupRole CHECK ([GroupRole] in ('Admin'))
CONSTRAINT [PK_Persons] PRIMARY KEY CLUSTERED
(
[PersonID] 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
My INSERT statement fails while it is trying to add a new record into an empty table (Attribute) (no record yet).
I am surprised by the error raised by the system:
Violation of UNIQUE KEY constraint 'CK_Attribute_Name_IDproject'. Cannot insert duplicate key in object 'dbo.Attribute'. The duplicate key value is (dummy, 55).
The creation script for this table looks like
CREATE TABLE [dbo].[Attribute](
[ID] [int] IDENTITY(1,1) NOT NULL,
[IDproject] [int] NOT NULL,
[IDtype] [int] NOT NULL,
[IDgroup] [int] NOT NULL,
[name] [varchar](50) NOT NULL,
[color] [int] NULL,
[protected] [tinyint] NULL,
[datemodified] [datetime] NOT NULL,
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],
CONSTRAINT [CK_Attribute_Name_IDproject] UNIQUE NONCLUSTERED
(
[name] ASC,
[IDproject] 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
I skiped foreign keys references and default values which does not seem of interest in this context.
The UNIQUE constraint applies to [name] and [IDproject].
When running the following statement
SELECT *
FROM [dbo].[Attribute]
GO
SELECT *
FROM [dbo].[Project]
GO
I get the results
(0 row(s) affected)
(2 row(s) affected)
The first result indicats the Attribute Table is empty
The second that there are 2 Projects
then running the following INSERT in table Attribute it failed with the above mentioned UNIQUE CONSTRAINT error
INSERT INTO [dbo].[Attribute] ([IDproject], [name], [IDtype], [IDgroup], [color], [protected], [datemodified])
SELECT DISTINCT
p.[ID],'dummy',t.[ID],g.[ID],-1,0,getdate()
FROM [dbo].[Project] p
INNER JOIN [dbo].[Group] g ON g.[name]='none' AND g.[IDproject] = p.[ID]
INNER JOIN [dbo].[AttributeType] t ON t.[format]='text' AND g.[IDproject] = p.[ID]
WHERE p.[name]='TESTPROJ'
GO
How can i get such an error on an empty table ?
I have found the solution myself: the derived SELECT returns 2 records with 'dummy' due to a duplicate INTO one of table, AttributeType, with which INNER JOIN is performed.