Solved

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

Posted on 2008-06-18
10
1,270 Views
Last Modified: 2010-04-21
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

0
Comment
Question by:DustinSpears
  • 7
  • 3
10 Comments
 
LVL 23

Accepted Solution

by:
Christopher Kile earned 500 total points
Comment Utility
Try including the constraint as a separate command (see the code snippet).  I admit it's a guess, but it can't hurt to try.
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))
 

ALter table ADD conSTRAINT fk_Div_Comp FOREIGN KEY (COMP_ID) REFERENCES COMPANY (COMP_ID) ON UPDATE CASCADE ON DELETE CASCADE

Open in new window

0
 

Author Comment

by:DustinSpears
Comment Utility
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.
0
 

Author Comment

by:DustinSpears
Comment Utility
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?
0
 

Author Comment

by:DustinSpears
Comment Utility
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?
0
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
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

0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 

Author Comment

by:DustinSpears
Comment Utility
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.
0
 
LVL 23

Expert Comment

by:Christopher Kile
Comment Utility
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

0
 

Author Comment

by:DustinSpears
Comment Utility
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?
0
 

Author Comment

by:DustinSpears
Comment Utility
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

0
 

Author Closing Comment

by:DustinSpears
Comment Utility
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.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video discusses moving either the default database or any database to a new volume.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now