Link to home
Start Free TrialLog in
Avatar of DustinSpears
DustinSpearsFlag for United States of America

asked on

Creating a table with a foreign key that has cascade on delete and update

Why does VB .Net code (with TSQL code being passed to SQL Server 2005) not correctly set the cascade on delete/update in the SQL database?

I know this is just a snippet, but the rest truly is uneccessary. If I copy past everything in quotes -- from "Create" to "VarChar(25)) " -- and paste in SQL Server Management Studio and run the query exactly as it is above, the table is created with the correct foreign key constraint AND the correct update/delete set to cascade.

If I run from my application, I get no errors. It connects fine, it creates the table, it creates the foreign key constraint. However, the Update/Delete are set to nothing, rather than cascade as they should be.
SQLComm = New SqlCommand("Create Table DIVISION (DIV_ID integer PRIMARY KEY, COMP_ID integer NOT NULL, CONSTRAINT fk_Div_Comp FOREIGN KEY (COMP_ID) REFERENCES COMPANY (COMP_ID) ON UPDATE CASCADE ON DELETE CASCADE, DivName VarChar(50) NOT NULL, DivStreet VarChar(200), DivCity VarChar(50), DivState VarChar(50), DivZip VarChar(25), DivPhone VarChar(25), DivFax VarChar(25))", Me.Conn, Me.Trans)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Christopher Kile
Christopher Kile
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DustinSpears

ASKER

Actually, I was previously having troubles using the Alter statement from within my application, which is why I moved the constraint into the create table portion of my code. I'll give it another shot though.
Yea, using the alter statement seperate actually doesn't even create the fk constraint at all. I'm thinking my sql login may not have the proper rights to do what I'm trying to do or something? But I'm not getting any exceptions either... any ideas?
How can I make sure that my login for the SQL Server / database I'm using has all the power necessary? I have it assigned as inheriting db_owner...I thought that would be enough?
Hmmmm...that wouldn't be the solution, unless you were logged into SSMS as a different user.  If you were logged in to SSMS with other credentials, log in with the same credentials as your application then attempt to run the script.....


OUCH.  I just realized...the table isn't created until the command finishes....Try executing each statement in its own command session, as in the code snippet.
sqlCMD.ExecuteNonQuery("Create Table DIVISION (.....",...)
sqlCmd.ExecuteNonQuery("ALter table ADD conSTRAINT fk_Div_Comp ...")

Open in new window

I log into SSMS with the exact same credentials, and the table does create with the constraint as I have it wrritnen above, all in one line. However, the only thing that fails, is the constraint does not set update/delete to "cascade". On top of that, I originally set it up as you have above, create table then alter to add the FK constraint, but that method does not add the FK at all. I'm getting a bit perpelexed.
You have no GO...that's why....

You see, until your CREATE TABLE command is committed, the ALTER TABLE has no table to alter.

The two pieces of the code snippet show the query I ran locally (notice it comes in three batches each terminated by 'GO') along with the script generated from the newly created fk_Div_Comp constraint.

That's why you need to execute the CREATE TABLE using one call to .ExecuteNonQuery and use another call to .ExecuteNonQuery to execute the ALTER TABLE command.


Script:
 
Create Table COMPANY (
COMP_ID integer NOT NULL PRIMARY KEY, 
CompanyName VarChar(50) NOT NULL)
go
 
Create Table DIVISION (
DIV_ID integer PRIMARY KEY, 
COMP_ID integer NOT NULL, 
DivName VarChar(50) NOT NULL, 
DivStreet VarChar(200), 
DivCity VarChar(50), 
DivState VarChar(50), 
DivZip VarChar(25), 
DivPhone VarChar(25), 
DivFax VarChar(25))
go
 
ALter table DIVISION ADD conSTRAINT fk_Div_Comp FOREIGN KEY (COMP_ID) REFERENCES COMPANY (COMP_ID) ON UPDATE CASCADE ON DELETE CASCADE 
go
 
Script representing changed ON DELETE|UPDATE behavior (generated by Query Manager):
 
ALTER TABLE [dbo].[DIVISION] ADD CONSTRAINT [fk_Div_Comp] FOREIGN KEY 
	(
		[COMP_ID]
	) REFERENCES [COMPANY] (
		[COMP_ID]
	) ON DELETE CASCADE  ON UPDATE CASCADE 
GO

Open in new window

Thats the thing, the original setup with the alter statement used after creating the table is in another function. In my test application, I hit a button to create the table (which works). Then I hit another button to create the references. The connection is opened/closed during each button press (therefore, by the time the alter statement is run the table does exist in the db. I even stop to check in SSMS before moving on to the button that uses the alter statement to create the fk relationship. Currently, even when the code is all in one line, it creats the table AND the FK relationship fine. But it does not set the update to cascade or the delete to cascade. =/ I did try your above code though. Any other ideas?
Oh man, I am an idiot. I had the actual SQL statement bundled up into a .dll that I was then referencing from the test app. Turns out I was referencing an old .dll in the debug folder, rather than the new .dll in the RELEASE folder. Hence, no matter what I did NOTHING changed. Wow, the initial code listed above in the problem works flawlessly know that it is ACTUALLY BEING RUN. I'll attach it for reference fi somebody else needs to see how to create a table, add fk, with delete/update cascades in the future.

Thanks for all your help cpkilekofp, sorry I put us through all this over something as simple as missreferncing a module of my project....
SQLComm = New SqlCommand("Create Table DIVISION (DIV_ID integer PRIMARY KEY, COMP_ID integer NOT NULL, CONSTRAINT fk_Div_Comp FOREIGN KEY (COMP_ID) REFERENCES COMPANY (COMP_ID) ON UPDATE CASCADE ON DELETE CASCADE, DivName VarChar(50) NOT NULL, DivStreet VarChar(200), DivCity VarChar(50), DivState VarChar(50), DivZip VarChar(25), DivPhone VarChar(25), DivFax VarChar(25))", Me.Conn, Me.Trans)
                    SQLComm.ExecuteNonQuery()

Open in new window

He was correct, however I did end up doing it the same way I had it the initial question. Completely my fault we were on this wild good chase.