H2 Composite Primary Key (fields get unique but not primary key) - database

I have a problem with a composite primary key in my h2 database table.
This is the create statement of the table:
CREATE TABLE IF NOT EXISTS TTColumn (
Name VARCHAR(15) NOT NULL,
TTName CHAR(8) NOT NULL,
Type VARCHAR(15) NOT NULL,
Length INTEGER NOT NULL,
Position INTEGER NOT NULL,
IsDBLogType BIT NOT NULL,
PRIMARY KEY(TTName,Name),
FOREIGN KEY(TTName) REFERENCES TrackingTable(Name))
(TTName is the name of the table for the columns, so its the same for each column of the table, but each column is unique in a table so its an composite key)
If i fill this table with data, i get the following exception
rg.h2.jdbc.JdbcSQLException: Eindeutiger Index oder Primärschlüssel verletzt: "CONSTRAINT_INDEX_E8 ON PUBLIC.TTCOLUMN(TTNAME) VALUES ('KIBLCOVI', 1)"
Unique index or primary key violation: "CONSTRAINT_INDEX_E8 ON PUBLIC.TTCOLUMN(TTNAME) VALUES ('KIBLCOVI', 1)"; SQL statement:
INSERT INTO TTColumn (Name,TTName,Type,Length,Position,IsDBLogType) VALUES (?,?,?,?,?,?) [23505-189]
As you can see the column "Name" is not part of the primary key anymore, like i defined in the create statement and i dont know why.
I have this problem in other tables too and adding the primary with alter table, after creating it, resolves in the same problem. When "Name" is the first column in the primary key, it gets the only column in the primary key, so the last entrys get removed.
I know, one solution would be to use id's, but I want to use a composite primary key, because i hate to add id's when its not necessary.
Is there something wrong with my create statement or do you have any other hints?
P.s. i tried the Version 1.4.189 and Version 1.3.176 as .jar (no server)
Edit:
Hmm, following the output from show columns:
NAME|VARCHAR(15)|NO|UNI|NULL|
TTNAME|CHAR(8)|NO|UNI|NULL|
TYPE|VARCHAR(15)|NO||NULL|
LENGTH|INTEGER(10)|NO||NULL|
POSITION|INTEGER(10)|NO||NULL|
ISDBLOGTYPE|BOOLEAN(1)|NO||NULL|
Somehow the column Name and TTName are UNI (Unique) but not a primary key.
if i change the order in the primary key declaration, the column TTName becomes a primary key field, but Name stays unique.

Related

Composite primary key in sql server

I am trying to create a composite primary key in Sql server.
The syntax I have tried is:
create table Installment_details
(
constraint P_key primary key(Account_No,month),
Account_No int not null,
foreign key (Account_No) references Account_details(Account_no) on delete cascade,
Month char(15) not null,
D#te date,
Receipt_no varchar(15),
Amount_received int,
Amount_left int,
Amount_receiver char(50),
)
As far as I know it should create column with column name P_key for primary key but whenever I make a entry in table it doesn't show this column.
You are confused about the terms you're using. It's not the same a Primary Key and a Column. For example, you're creating a Primary Key based on two existing columns, and the name P_Key it's the name of the Primary Key, which is the way SQL SERVER (in this case) can identify a row in the Table (it cannot be two rows with the same values on those two columns).
I hope this clarifies a little bit the issue.
I think you are getting it wrong P_key in your code is constraint's name not a column name.
Also composite key is not a column, it is used when you don't have a column with unique values. So you take combination of two or more column as primary key so that we can uniquely identify a row.

Entity Framework appears to skip mapping a table with a multi-column primary key set through a constraint

I've created an ADO.NET model via the database first approach.
One of my tables which is listed when creating the model doesn't actually get added to it.
The table has a multi-column primary key, composed of two foreign keys.
CREATE TABLE ForumAccess
(
UserID INT FOREIGN KEY REFERENCES Users(UserID) NOT NULL,
ForumID INT FOREIGN KEY REFERENCES Forums(ForumID) NOT NULL,
CONSTRAINT ForumAccessID PRIMARY KEY (UserID, ForumID),
);
It does show up when I have to select which tables to add, but then it seems to be skipped. No class is generated for it, and it's not shown in the .edmx file.
Part of my application depends on the existence of this table. I have another table which has a multi-column primary key, and another DateTime type column. That table does get added.
That table is:
CREATE TABLE Moderators
(
UserID INT FOREIGN KEY REFERENCES Users(UserID) NOT NULL,
ForumID INT FOREIGN KEY REFERENCES Forums(ForumID) NOT NULL,
TimeOfAddition DateTime NOT NULL, -- When the mod was added as a mod.
CONSTRAINT ModeratorID PRIMARY KEY (UserID, ForumID),
);
Why does the Moderators table get added, but the ForumAccess table doesn't?
There is no error, or any warning that I can see.
What am I missing?

Foreign Key on unique index doesn't work with NULL column

I am struggling with a foreign key on a unique index in SQL Server, which isn't quite working as expected.
My table structure is like this:
Table mm1 has a nonclustered PK-Index on a surrogate key column id
Additionally mm1 has a clustered unique index on three columns (one of them is nullable)
Table mm2 links on those three columns via a foreign key
The creation of these objects doesn't throw any errors. However, the foreign key is not evaluted properly and allows for non-existing values in mm1 to be inserted in mm2. This seems to be related on the nullable column c....if I set the foreign key on just columns a and b it works as expected.
Can you explain this behaviour? Why allowing to define a unique index including null in the first place but not supporting it properly in foreign key constraints? Is there a way to achieve correct results without changing contents of table mm2?
Here's a little repro script:
CREATE table mm1 (
id int identity(1,1) NOT NULL,
a varchar(50) not null,
b int not null,
c int null,
PRIMARY KEY NONCLUSTERED(id))
CREATE table mm2 (
id int identity(1,1) NOT NULL,
a varchar(50) not null,
b int not null,
c int null,
d varchar(10),
PRIMARY KEY NONCLUSTERED(id))
CREATE UNIQUE CLUSTERED INDEX idx_mm1_mm_fkTest1 ON mm1(a,b,c)
ALTER TABLE mm2
ADD CONSTRAINT fk_mm2_mm_fkTest1
FOREIGN KEY (a,b, c)  REFERENCES mm1(a,b,c)
ALTER TABLE mm2 CHECK CONSTRAINT fk_mm2_mm_fkTest1;
INSERT INTO mm1 VALUES ('abc', 1, 2);
INSERT INTO mm2
(a,b,d) VALUES('sa',1,'sad')
SELECT * FROM mm2;
I am not at all sure what I would expect this to do. The more I think about it, the less sense it makes.
NULL is evaluated in these contexts to mean UNKNOWN. With an unknown in a foreign key you can never be sure which row it refers to in the first place. In other words, this constraint makes no semantic sense.
Use a default value and have your foreign key hit non-null values only. If you allow NULLs in foreign keys they will be dangling anyway.

Issue in mapping a new table data to an existing table

I have a parent table like below
CREATE TABLE "Tablename"
(
"column1" integer,
"column2" integer NOT NULL,
"column3" text,
"column4" integer,
"column5" text,
"column6" integer,
CONSTRAINT "Tablename_pkey" PRIMARY KEY ("column1"),
CONSTRAINT uk_t1 UNIQUE ("column2")
);
so in the above table, column2 is Unique&Not Null which means primary key??
I am trying to assign column2 as Foreign Key in another table but I get the error like below
ERROR: there is no unique constraint matching given keys for referenced table "Tablename"
SQL state: 42830
Note If I assign the column2 as Primary Key directly in the parent table, then I am able to assign it as a Foreign Key in the child table. Here I can't do that. I need help for the same!
The following worked from psql. Are you just having a syntax problem?
CREATE TABLE foo
(column2 integer not null,
FOREIGN KEY (column2) REFERENCES "Tablename"(column2)
);

How can I have a foreign key that points to a computed column?

I have this table:
CREATE TABLE [dbo].[Question] (
[QuestionId] INT IDENTITY (1, 1) NOT NULL,
[Text] NVARCHAR (4000) NULL,
[QuestionUId] UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
);
I would like to create a foreign key linking QuestionUId in my other table AdminTestQuestion back to the QuestionUId in the Question table.
The referenced table '[dbo].[Question]' contains no primary or candidate keys that match the referencing column list in the foreign key. If the referenced column is a computed column, it should be persisted.
Any advice would be much appreciated.
First of all: this is really NOT a computed column - it's just a regular column with a default constraint...
For a column in a table to be used for a foreign key reference, it must be either the primary key of that table, or it has to have a unique index on it.
So here, all you need to do is to add a unique index on your column
CREATE UNIQUE INDEX UIX_QuestionUid ON dbo.Question(QuestionUid)
and then you should be able to reference it as a foreign key.

Resources