Click here to Skip to main content
15,885,244 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am creating and updating two tables
one table is having foregin key with other table
while updating table I am getting error so I want to turn off
oregin key while update.so I wrote one command As Mentioned in net. But it is showing syntax error. Blow is the Code.I am unable to run also

SqlCommand scmd = new SqlCommand("EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"", con);


What I have tried:

I checked for solution but failed
Posted
Updated 27-Jun-17 21:52pm

1 solution

Well... double quote ends a C# string ...

So you need to escape it if you want to pass a double quote to SQL:
SqlCommand scmd = new SqlCommand("EXEC sp_MSforeachtable \"ALTER TABLE ? NOCHECK CONSTRAINT all\"", con);
Or
SqlCommand scmd = new SqlCommand(@"EXEC sp_MSforeachtable ""ALTER TABLE ? NOCHECK CONSTRAINT all""", con);
But you might find that this works better with SQL:
SqlCommand scmd = new SqlCommand("EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'", con);
 
Share this answer
 
Comments
vijay_bale 28-Jun-17 4:28am    
thank you. It worked. I took the last one you told. But how I enable the constrains after updating record.
vijay_bale 28-Jun-17 4:37am    
I gave below one to re enable constrain
SqlCommand md=new SqlCommand("exec sp_MSforeachtable @command1 = 'print' '?', @command2 = 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'",con);
md.ExecuteNonQuery();

But It Gave "incorrect syntax near '?'.
OriginalGriff 28-Jun-17 5:13am    
It's probably the question mark - it doesn't know which table you are working on.

But to be honest, if you have to disable constraints to update records, then there is probably something wrong with your data or your design. You should just have to do the updates in the right order, not disable checking.
vijay_bale 28-Jun-17 5:24am    
Ok I will look for that what you told. But anyhow how to enable that
vijay_bale 28-Jun-17 5:47am    
Can I post A new Question For that?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900