Strange constraints in generated SQL - sql

Note: This question is not related to Visual Paradigm. Anyone that knows SQL could answer it.
I am using Visual Paradigm to model a database in our project (using ER diagrams). When Visual Paradigm generates the SQL equivalent for the database and I import it in MSSQL it works pretty.
I took a look in generated SQL code to make sure anything is right and I saw something strange!:
For tblContracts I defined a constraint named EndAfterStart to make sure the value of endDate is always bigger than startDate. The generated SQL code for this constraint is here:
IF NOT EXISTS (SELECT * FROM sys.check_constraints WHERE object_id=OBJECT_ID(N'[dbo].[EndAfterStart]'))
ALTER TABLE [dbo].[tblContracts] WITH CHECK ADD CONSTRAINT [EndAfterStart] CHECK (([startDate]<=[endDate]))
GO
ALTER TABLE [dbo].[tblContracts] CHECK CONSTRAINT [EndAfterStart]
GO
And the questions:
Why tblContracts is altered twice to add this constraint?!
Isn't first two lines enough?
What is different between second line and forth line?

First and second lines create EndAfterStart constraint if it doesn't exist. Fourth line enables EndAfterStart constraint.

The second line adds the constraint to the table; the fourth line enables the constraint.

Related

Create field constraint based on another table field in LibreOffice Base

I have 3 tables, "Courses"(id, start_date), "Subscriptions"(id, assistant_id, course_id, date) and "Assistants"(id, registration_date).
Subscriptions reference Courses and Assistants with foreign keys as you see.
I need to add CHECK constraint that will prevent to create Subscription record if referenced Courses.start_date is older than referenced Assistants.registration_date. Is there a way to do this in Libre Base?
Table organization could not be changed.
Such a CHECK constraint cannot be created with the default engine. From the HSQLDB 1.8 documentation:
ALTER TABLE <tablename> ADD [CONSTRAINT <constraintname>]
CHECK (<search condition>);
Adds a check constraint to the table. In the current version, a check constraint can reference only the row
being inserted or updated.
This means that commands like the following from TestSelfCheckConstraints.txt produce an error:
/*e*/CREATE TABLE TC6(A CHAR, B CHAR, C CHAR, D INT, CHECK(A IN (SELECT A FROM
TC5)));
So, to perform such a check, you will have to verify it ahead of time (or afterwards) using a query. This could be done for a form by adding a macro in the Events tab. See this post for ideas: https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=21414.
The default engine is rather old, so for such complex requirements it may be better to set up LibreOffice Base to use a different database engine. For example using MySQL, it is possible to set up a stored procedure trigger to do this kind of checking. See CHECK constraint in MySQL is not working.

Microsoft Access - SQL command to add a constraint

I Am new in stackoverflow and whats worst is I am new to Microsoft Access. My homework
Assume the Part table has been created, but there are no integrity constraints. Create the necessary integrity constraint to ensure that the only allowable values for the Class field are AP, HW, and SG. Ensure that the PartNum field is the primary key and that the PartNum field in the OrderLine table is a foreign key that must match the primary key of the Part table.
So I know how to create this by using Microsoft Access by going to the Validation Rule and add validation for AP, HW, and SG. However, I need to also create the query to show how this is done.
My code:
ALTER TABLE Parts
ADD CONSTRAINT classRule
CHECK IN Class(AP, HW, SG)
;
My textbook has an example which is similar to what I just wrote above. When I run this I get a Constraint error. What am I doing wrong? Also, the foreign key and primary key have already been made so I just need to write the sql query to display my result. Any help is appreciated!
The CHECK clause exists but it's not a particularly good idea to use it because it can create issues in you application.
That being said, your constraint should work but there are a couple things:
You should avoid the use of the word Class as a field name. It's not a reserved word per se, but it's a VBA reserved word and while Access let you create that field, you may encounter strange problems elsewhere later.
As Brian said, you need to use single quotes for string literals in your CHECK
You can't create CONTRAINT with CHECK from the SQL Query Editor in Access, you'll get errors on the CHECK part every time you try.
Instead you need to execute the DDL SQL from VBA: just open the VBA (Alt+F11) then type the following in the Immediate Window (Ctrl-G if you don't see it), then press ENTER:
CurrentProject.Connection.Execute "ALTER TABLE Parts ADD CONSTRAINT ClassRule CHECK (Class IN ('AP', 'HW', 'SG'));"
If you don't get an error, then the constraint was properly executed, otherwise, double check that the syntax is correct, field names, parenthesis are properly balanced, and that the Part table is not open.
You probably want:
ALTER TABLE Parts
ADD CONSTRAINT classRule
CHECK (class in ('AP', 'HW', 'SG'));
There is a space between CONSTRAINT and the name
Put conditions within the () after the CHECK keyword
Put literals within single quotes, as this is what differentiates field names from values
Edit
Although the above is valid syntax, from what I'm reading you may not be able to add a check constraint in Access via writing out the SQL, at least not in the SQL view of query designer.
You can add a check constraint by going to Design View for the table of interest, then on the row representing the column of interest, type the following on the line for "Validation Rule":
in ('AP', 'HW', 'SG')
http://www.databaseskill.com/1942875/
"Note The check constraint statement can only be executed through the Jet OLE DB provider and ADO; it will return an error message if used though the Access SQL View user interface."
Above quote is from the URL I just provided.

Power designer, generate procedures before tables

I am using Power Designer to create a database model. In one of my tables, I have created a Check constraint that calls a function to validate the attribute. The script for my table creation looks like this
create table tbl_Inventory (
Id int identity,
Name VARCHAR(50) not null
constraint CK_Inventory_Name check (([dbo].[fn_CheckNameComplexLogic]([Name]) = 1)),
constraint PK_Inventory primary key (Id),
)
I have also created a function fn_CheckNameComplexLogic that performs the check.
When I try to use the code generation tool by going Database->Generate Database. The generated code always place create table before create function. Because my table depends on the function, the scripts always errors out. I could manually edit the generated code, but I am wondering if there is a place in PowerDesigner for configuring this.
Thanks for your help.
If may be a little overkill, but you can change the Generation Order to put (all) the functions (included in the Procedure category) before the Table.
embed the DBMS in your model with Database>Change Current DBMS
edit it with Database>Edit Current DBMS
change the order in the Script\Objects\GenerationOrder item (using the XML view)
put Procedure above Table
Simply add condition into Additional Checks of column properties tab after all constructs like %MINMAX% and %LISTVAL% and %CASE% and %RULES% and write here your condition ...

symfony doctrine build-sql error

I have some big problems with symfony and doctrine at the beginning of a new project. I have created database diagram with mysql workbench, inserted the sql into phpmyadmin and then I've tried symfony doctrine:build-schema to generate the YAML schema.
It generates a wrong schema (relations don't have on delete/on update) and after this I've tried symfony doctrine:build --sql and symfony doctrine:insert-sql
The insert-sql statement generates error (can't create table ... failing query alter table add constraint ....), so I've decided to take a look over the generated sql and I've found out some differences between the sql generated from mysql workbench (which works perfect, including relations) and the sql generated by doctrine.
I'll be short from now: I have to tables, EVENT and FORM and a 1 to n relation (each event may have multiple forms) so the correct constraint (generated with workbench) is
ALTER TABLE `form` ADD CONSTRAINT `fk_form_event1` FOREIGN KEY (`event_id`) REFERENCES `event` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
doctrine generated statement is:
ALTER TABLE event ADD CONSTRAINT event_id_form_event_id FOREIGN KEY (id) REFERENCES form(event_id);
It's totally reversed and I am sure here is the error. What should I do? It's also correct like this?
It it broken, I've wrote the schema manually and it works perfect. I didn't want to do that because it was a very large file, but I've also learned from it!
Thank you guys!
To get both visual representation and automatic code generation you can use ORM Designer so you will have everything covered by one tool.

sql server helper stored procedure or utility for alter table alter column IDENTITY(1,1)

I wanted to modify a column in a sql server 2005 table to IDENTITY(1,1)
Incidentally this table is empty and the column to be changed is a primary key.
This column is also a foreign key for two other tables.
After googling I found that you cannot use Alter table syntax to modify a column and make it an indentity column.
Link #1 : How do I add the identity property to an existing column in SQL Server
Link #2 : Adding an identity to an existing column -SQL Server
I ended up checking the dependent tables (2 of them) removing the foreign keys (generated the script from SSMS) then dropping the main table then re-creating with identity. (could try the rename option here as well)
Then re-created the foreign keys for the earlier dependent two tables.
But all this was manual work, any scripts or SPs out there to make this easier.
Ideally all these steps would be done by such a script/tool/utility:
Check dependent tables keys
Generate Create and drop foreign key scripts for this
Generate create script for the main table
drop the main table (or rename the table if the table has data)
re-create the table with identity column enabled
re-create foreign keys
You can use SSMS to generate a script (Edit a table, save script), but otherwise it's a manual process as you identified.
The SSMS scripts will pick up dependencies etc. For this kind of work, I tend to use SSMS to generate a basic script, pimp it a bit, run it carefully, then use a comparison tool (such as Red Gate compare) to generate a safer version.
Edit: The SSMS error is not an error, it's a safety check that can be switched off
(This is merely a follow-up to gbn's post with more details -- it isn't all that easy to figure this stuff out.)(
It isn't impossible to write a utility to do this, just very complex and very hard. Fortunately, Microsoft has already done it -- its called SSMS (or SMO?). To generate such a script:
In the Object Explorer, drill down to the database and table that you want to modify
Right click and select Design
Make the desired changes to the one table in the design screen. It's reasonably intuitive.
To add/remove the identity property, select the column in the upper pane, and in the lower pane/"Column Properties" tab, expand and configure the settings under "Identity Specification".
To generate a script to implement all your changes, incorporating all the dependent key changes, click on the "Generate Change Script" toolbar button. This is also an option under the "Table Designer" menu.
I also do this to generate scripts (that I later modify--SSMS doesn't always produce the most efficient code.) Once done, you can exit out without saving your changes -- leaving you a DB you can test your new script on.
drop the pk and build the same datatype column
copy the data of the column which you want to set identity to the new column.
drop the old column
reset primary key
ALTER TABLE UserRole
DROP CONSTRAINT PK_XX
ALTER TABLE XX
ADD newX int not null identity(1,1) primary key
update XX set newX = oldX
alter table XX
DROP COLUMN oldX
this is the simplest way to set identity column.
if you don't want to use the long generated script.