Solved

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

Posted on 2008-06-18
10
1,297 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 3
10 Comments
 
LVL 23

Accepted Solution

by:
Christopher Kile earned 500 total points
ID: 21814230
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
ID: 21814293
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
ID: 21814372
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
Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

 

Author Comment

by:DustinSpears
ID: 21814425
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
ID: 21815549
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
 

Author Comment

by:DustinSpears
ID: 21815605
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
ID: 21815731
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
ID: 21816004
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
ID: 21816064
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
ID: 31468535
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

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …

717 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