Composite primary key in sql server - 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.

Related

Creating in MS-SQL a primary key results in a dynamic index name format eg PK__dummy__3213E83F2E1BDC42

Hope for help because of the following problem. Assume we have a table
CREATE TABLE [dbo].[dummy](
[id] [char](36) NOT NULL,
[name] [varchar](50) NOT NULL
) ON [PRIMARY]
If I create a primary key like this (version 1)
ALTER TABLE dummy ADD CONSTRAINT PK_dummy PRIMARY KEY (ID);
I get a unique name. In this case PK_dummy.
But if I create a primary key like this (version 2)
ALTER TABLE dummy ADD PRIMARY KEY Clustered (ID);
The name changes with every recreation of this primary key.
The format is always PK__dummy__"a dynamic number"
What is the meaning of this number?
And how can I identify primary keys created with version 2 in a hugh database?
Thanks for hints.
What is the meaning of this number?
This depends on product version - it is either based on a unique id or generated randomly.
how can I identify primary keys created with version 2 in a huge database?
SELECT *
FROM sys.key_constraints
WHERE is_system_named = 1
If you don't define the name of a constraint, index, key, etc, SQL Server will give it a name. To ensure uniqueness across the database, it therefore will add "random" characters at the end.
If having a consistent name is important then define the name in your statement, as you did in the first statement.

How to add another primary key in SQL Server

I have a SQL Server table that has primary keys
CompanyID
ClientID
ReportName
I need to add a column that is an additional key and an incremented ID.
alter table Exports
add id int identity(1,1)
How do I write the statement to make this a key as well?
You can have only 1 primary key or identity column in each table in SQL Server.
If you want to have one more column as primary key, then you may use the combination of the columns as the primary key.
Or you can set the constraints UNIQUE and NOT NULL to the columns so that they will act same as a primary key (but these columns can't be referred as foreign keys)
In case of auto incremental columns (identity), you can only have 1 identity column per table. It can also be set as a primary key. Otherwise, if you need multiple columns as auto-increment, then probably you can use a calculated column, a trigger or a sequence object from which you may fetch the values for each record

T-SQL inserting data into table with foreign key

I'm using SQL Server 2014 to create and insert data into tables and came along a problem when it comes to populating a table with a foreign key constraint in it. I have a table user and and a table city which were created beforehand.
I used code to alter the user table to include a cityId foreign key from table city with this code:
ALTER TABLE [Schema].[user]
ADD cityId UNIQUEIDENTIFIER NOT NULL
CONSTRAINT usr_cid_fk
FOREIGN KEY (cityId) REFERENCES [Schema].[city] (cityId);
GO
Basically I modified the user table by adding a field called cityId which i made foreign key. now the problem is that when inserting data, in the first line
INSERT INTO [Schema].[user](name, surname, dob, gender, .. )
cityId cannot be found to be mapped. Dunno why it ain't showing. In the design view it is listed as a foreign key so there should be no problems.
Thanks a lot
try :
ALTER TABLE [Schema].[user]
ADD cityId NUMBER NOT NULL
CONSTRAINT usr_cid_fk
FOREIGN KEY (cityId) REFERENCES [Schema].[city] (cityId);
Note :
For ADD cityId UNIQUEIDENTIFIER NOT NULL
By the SQL standard, a foreign key must reference either the primary key or a unique key of the parent table. If the primary key has multiple columns, the foreign key must have the same number and order of columns. Therefore the foreign key references a unique row in the parent table; there can be no duplicates.

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

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.

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