Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2008-06-18
10
Medium Priority
?
1,309 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 2000 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

618 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