Solved

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

Posted on 2008-06-18
10
1,285 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
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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

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

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.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
.NET 2008 VB and C# 6 39
Expression Evaluater 3 38
run a stored procedure from vb.net 1 27
Clone table from one server.database to another server.database 24 39
Introduction: When running hybrid database environments, you often need to query some data from a remote db of any type, while being connected to your MS SQL Server database. Problems start when you try to combine that with some "user input" pass…
In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

808 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