I currently have:
CREATE TABLE galleries_gallery ( id INT NOT NULL PRIMARY KEY IDENTITY, title NVARCHAR(50) UNIQUE NOT NULL, description VARCHAR(256), templateID INT NOT NULL REFERENCES galleries_templates(id), jsAltImgID INT NOT NULL REFERENCES libraryImage(id) jsAltText NVARCHAR(500), dateCreated SMALLDATETIME NOT NULL, dateUpdated SMALLDATETIME NOT NULL, lastUpdatedBy INT, deleted BIT NOT NULL DEFAULT 0 );
But this adds constraints with auto generated names which make it hard to drop the constraint later. What do I need to add in order to name the constraints?
The above example is SQL Server and I also need it in PostgreSQL.
The table name (in our example, student ) is placed after the ALTER TABLE keyword. Next, the ADD FOREIGN KEY clause is followed by the name of the column that will be used as the foreign key. Then we have the REFERENCES clause with the name of the referenced table and the name of the primary key column in parentheses.
To create a SQL foreign key constraint, the parent table should have primary key column or column with UNIQUE constraint. In this case, table Dept is parent table which has Primary key and will be referenced in child tables having foreign key.
The syntax for creating a foreign key using an ALTER TABLE statement in SQL Server (Transact-SQL) is: ALTER TABLE child_table ADD CONSTRAINT fk_name FOREIGN KEY (child_col1, child_col2, ... child_col_n) REFERENCES parent_table (parent_col1, parent_col2, ...
In SQL Server, you can use the constraint
keyword to define foreign keys inline and name them at the same time.
Here's the updated script:
CREATE TABLE galleries_gallery ( id INT NOT NULL PRIMARY KEY IDENTITY, title NVARCHAR(50) UNIQUE NOT NULL, description VARCHAR(256), templateID INT NOT NULL CONSTRAINT FK_galerry_template REFERENCES galleries_templates(id), jsAltImgID INT NOT NULL CONSTRAINT FK_gallery_jsAltImg REFERENCES libraryImage(id) jsAltText NVARCHAR(500), dateCreated SMALLDATETIME NOT NULL, dateUpdated SMALLDATETIME NOT NULL, lastUpdatedBy INT, deleted BIT NOT NULL DEFAULT 0 );
I just made a test and apparently the same thing also works in PostgreSQL: http://www.sqlfiddle.com/#!12/2ae29
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With