There are two questions which I get every single day multiple times. In my gmail, I have created standard canned reply for them.
Let us see the questions here.
I want to delete from multiple table in a single statement how will I do it?
I want to update multiple table in a single statement how will I do it?
The answer is – No, You cannot and you should not.
SQL Server does not support deleting or updating from two tables in a single update. If you want to delete or update two different tables – you may want to write two different delete or update statements for it. This method has many issues – from the consistency of the data to SQL syntax.
Now here is the real reason for this blog post – yesterday I was asked this question again and I replied my canned answer saying it is not possible and it should not be any way implemented that day. In the response to my reply I was pointed out to my own blog post where user suggested that I had previously mentioned this is possible and with demo example. Let us go over my conversation – you may find it interesting. Let us call the user DJ.
DJ: Pinal, can we delete multiple table in a single statement or with single delete statement?
Pinal: No, you cannot and you should not.
DJ: Oh okey, if that is the case, why do you suggest to do that?
Pinal: (baffled) I am not suggesting that. I am rather suggesting that it is not possible and it should not be possible.
DJ: Hmm… but in that case why did you blog about it earlier?
Pinal: (What?) No, I did not. I am pretty confident.
DJ: Well, I am confident as well. You did.
Pinal: In that case, it is my word against your word. Isn’t it?
DJ: I have proof. Do you want to see it that you suggest it is possible?
Pinal: Yes, I will be delighted too.
(After 10 Minutes)
DJ: Here are not one but two of your blog posts which talks about it -
SQL SERVER – Curious Case of Disappearing Rows – ON UPDATE CASCADE and ON DELETE CASCADE – Part 1 of 2
SQL SERVER – Curious Case of Disappearing Rows – ON UPDATE CASCADE and ON DELETE CASCADE – T-SQL Example – Part 2 of 2
Pinal: Oh!
DJ: I know I was correct.
Pinal: Well, oh man, I did not mean there what you mean here.
DJ: I did not understand can you explain it further.
Pinal: Here we go.
The example in the other blog is the example of the cascading delete or cascading update. I think you may want to understand the concept of the foreign keys and cascading update/delete. The concept of cascading exists to maintain data integrity. If there primary keys get deleted the update or delete reflects on the foreign key table to maintain the key integrity and data consistency. SQL Server follows ANSI Entry SQL with regard to referential integrity between PrimaryKey and ForeignKey columns which requires the inserting, updating, and deleting of data in related tables to be restricted to values that preserve the integrity. This is all together different concept than deleting multiple values in a single statement.
When I hear that someone wants to delete or update multiple table in a single statement what I assume is something very similar to following.
DELETE/UPDATE Table 1 (cols) Table 2 (cols)
VALUES … which is not valid statement/syntax as well it is not ASNI standards as well.
I guess, after this discussion with DJ, I realize I need to do a blog post so I can add the link to this blog post in my canned answer. Well, it was a fun conversation with DJ and I hope it the message is very clear now.
Reference: Pinal Dave (http://blog.SQLAuthority.com)
Filed under: PostADay, SQL, SQL Authority, SQL Joins, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology
On some servers we have many old Virtual Directories created for previous versions of our application.
IIS user interface allows to delete only one in a time.
Fortunately we can use IIS scripts as described in
How to manage Web sites and Web virtual directories by using command-line scripts in IIS 6.0
I've created batch file DeleteOldVDirs.cmd
rem http://support.microsoft.com/kb/816568
rem syntax: iisvdir /delete WebSite [/Virtual Path]Name [/s Computer [/u [Domain\]User /p Password]]
REM list all directories and create batch of deletes
iisvdir /query "Default Web Site"
echo "Enter Ctrl-C if you want to stop deleting"
Pause
iisvdir /delete "Default Web Site/VDirName1"
iisvdir /delete "Default Web Site/VDirName2"
...
If the name of WebSite or Virtual directory contain spaces(e.g "Default Web Site"), don't forget to use double quotes.
Note that the batch doesn't delete physical directories from flie system.You need to delete them using Windows Explorer, but it does support multiple selection!
I've been trying to figure this out for hours now, and I'm at my wit's end. I would surely appreciate it if someone could tell me when I'm doing wrong.
I have written a simple class to emulate basic functionality of strings. The class's members include a character pointer data (which points to a dynamically created char array) and an integer strSize (which holds the length of the string, sans terminator.)
Since I'm using new and delete, I've implemented the copy constructor and destructor. My problem occurs when I try to implement the operator+=. The LHS object builds the new string correctly - I can even print it using cout - but the problem comes when I try to deallocate the data pointer in the destructor: I get a "Heap Corruption Detected after normal block" at the memory address pointed to by the data array the destructor is trying to deallocate.
Here's my complete class and test program:
#include <iostream>
using namespace std;
// Class to emulate string
class Str {
public:
// Default constructor
Str(): data(0), strSize(0) { }
// Constructor from string literal
Str(const char* cp) {
data = new char[strlen(cp) + 1];
char *p = data;
const char* q = cp;
while (*q)
*p++ = *q++;
*p = '\0';
strSize = strlen(cp);
}
Str& operator+=(const Str& rhs) {
// create new dynamic memory to hold concatenated string
char* str = new char[strSize + rhs.strSize + 1];
char* p = str; // new data
char* i = data; // old data
const char* q = rhs.data; // data to append
// append old string to new string in new dynamic memory
while (*p++ = *i++) ;
p--;
while (*p++ = *q++) ;
*p = '\0';
// assign new values to data and strSize
delete[] data;
data = str;
strSize += rhs.strSize;
return *this;
}
// Copy constructor
Str(const Str& s)
{
data = new char[s.strSize + 1];
char *p = data;
char *q = s.data;
while (*q)
*p++ = *q++;
*p = '\0';
strSize = s.strSize;
}
// destructor
~Str() { delete[] data; }
const char& operator[](int i) const { return data[i]; }
int size() const { return strSize; }
private:
char *data;
int strSize;
};
ostream& operator<<(ostream& os, const Str& s)
{
for (int i = 0; i != s.size(); ++i)
os << s[i];
return os;
}
// Test constructor, copy constructor, and += operator
int main()
{
Str s = "hello"; // destructor for s works ok
Str x = s; // destructor for x works ok
s += "world!"; // destructor for s gives error
cout << s << endl;
cout << x << endl;
return 0;
}
Hi, Does anyone know how to delete an object and all of it's related entities.
For example i have tables, Products, Category, ProductCategory and productDetails, the productCategory is joining table of both Product and Category.
I have red from http://msdn.microsoft.com/en-us/library/bb738580.aspx that Deleting the parent object also deletes all the child objects in the constrained relationship. This result is the same as enabling the CascadeDelete property on the association for the relationship.
I am using this code
Product productObj = this.ObjectContext.Product.Where(p => p.ProductID.Equals(productID)).First();
if (!productObj.ProductCategory.IsLoaded)
productObj.ProductCategory.Load();
if (!productObj.ProductDetails.IsLoaded)
productObj.ProductDetails.Load();
//my own methods.
base.Delete(productObj);
base.SaveAllObjectChanges();
But i am getting error on ObjectContext.SaveChanges(); i.e
A relationship is being added or deleted from an AssociationSet 'FK_ProductCategory_Product'. With cardinality constraints, a corresponding 'ProductCategory' must also be added or deleted.
Thanks in advance....
Hey,
I know this is bit of a strange one but if anyone had any help that would be greatly appreciated.
The scenario is that we have a production database at a remote site and a developer database in our local office. Developers make changes directly to the developer db and as part of the deployment process a C# application runs and produces a series of .sql scripts that we can execute on the remote side (essentially delete *, insert) but we are looking for something a bit more elaborate as the downtime from the delete * is unacceptable. This is all reference data that controls menu items, functionality etc of a major website.
I have a sproc that essentially returns a diff of two tables. My thinking is that I can insert all the expected data in to a tmp table, execute the diff, and drop anything from the destination table that is not in the source and then upsert everything else.
The question is that is there an easy way to do this without using a cursor? To illustrate the sproc returns a recordset structured like this:
TableName Col1 Col2 Col3
Dest
Src
Anything in the recordset with TableName = Dest should be deleted (as it does not exist in src) and anything in Src should be upserted in to dest. I cannot think of a way to do this purely set based but my DB-fu is weak.
Any help would be appreciated. Apologies if the explanation is sketchy; let me know if you need anymore details.
Hi folks,
We have a linux system (kubuntu 7.10) that runs a number of CORBA Server processes.
The server software uses glibc libraries for memory allocation.
The linux PC has 4G physical memory. Swap is disabled for speed reasons.
Upon receiving a request to process data, one of the server processes allocates a large data buffer (using the standard C++ operator 'new'). The buffer size varies depening upon a number of parameters but is typically around 1.2G Bytes. It can be up to about 1.9G Bytes. When the request has completed, the buffer is released using 'delete'.
This works fine for several consecutive requests that allocate buffers of the same size or if the request allocates a smaller size than the previous.
The memory appears to be free'd ok - otherwise buffer allocation attempts would eventually fail after just a couple of requests.
In any case, we can see the buffer memory being allocated and freed for each request using tools such as KSysGuard etc.
The problem arises when a request requires a buffer larger than the previous.
In this case, operator 'new' throws an exception.
It's as if the memory that has been free'd from the first allocation cannot be re-allocated even though there is sufficient free physical memory available.
If I kill and restart the server process after the first operation, then the second request for a larger buffer size succeeds. i.e. killing the process appears to fully release the freed memory back to the system.
Can anyone offer an explanation as to what might be going on here?
Could it be some kind of fragmentation or mapping table size issue?
I am thinking of replacing new/delete with malloc/free and use mallopt to tune the way the memory is being released to the system.
BTW - I'm not sure if it's relevant to our problem, but the server uses Pthreads that get created and destroyed on each processing request.
Cheers,
Brian.
I have a lookup table (##lookup). I know it's bad design because I'm duplicating data, but it speeds up my queries tremendously. I have a query that populates this table
insert into ##lookup select distinct col1,col2,... from table1...join...etc...
I would like to simulate this behavior:
delete from ##lookup
insert into ##lookup select distinct col1,col2,... from table1...join...etc...
This would clearly update the table correctly. But this is a lot of inserting and deleting. It messes with my indexes and locks up the table for selecting from.
This table could also be updated by something like:
delete from ##lookup where not in (select distinct col1,col2,... from table1...join...etc...)
insert into ##lookup (select distinct col1,col2,... from table1...join...etc...) except if it is already in the table
The second way may take longer, but I can say "with no lock" and I will be able to select from the table.
Any ideas on how to write the query the second way?
Hi Everyone!
I am attempting to clean out a table but not get rid of the actual structure of the table, i have the following columns: id, username, date, text
the id is auto incrementing, I don't need to keep the ID number, but i do need it to keep its auto-incrementing characteristic. I've found delete and truncate but I'm worried one of these will completely drop the entire table rendering future insert commands useless.
Thank you, Everybody!
I was looking for a way to avoid deleting my users from DB, but instead to mark them as deleted and don't bring them back in queries.
I found this plugin http://grails.org/plugin/hibernate-filter, which was a great tool for the task.
But when I tried to implement my solution, I passed trought same problems whose solutions wheren't (or I was not able to find) on internet.
So, next, I describe the way that I solve the problem of soft delete.
How do you delete all the contents of a directory without deleting the directory itself? I want to basically empty a folder yet leave it (and the permissions) intact.
Can I delete the old rectangle which I have drawn and draw a new rectangle?
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
Graphics g = this.panel1.CreateGraphics();
Pen pen = new Pen(Color.Black, 2);
g.DrawRectangle(pen, 100,100, 100, 200);
g.dispose();
}
Can I delete the old rectangle which I have drawn and draw a new rectangle?
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
Graphics g = this.panel1.CreateGraphics();
Pen pen = new Pen(Color.Black, 2);
g.DrawRectangle(pen, 100,100, 100, 200);
g.dispose();
}
Hi,
If I delete every keys in a ColumnFamily in a Cassandra db using remove(key), then if I use get_range_slices, rows are still there but without columns. How could I remove entire rows?
Thanks
Tobia Loschiavo
Dim db As New SQLDataContext
Try
Dim deleteBoatPics = (From boat In db.Photos
Where boat.boatid = id)
db.Photos.DeleteOnSubmit(deleteBoatPics)
db.SubmitChanges()
Catch ex As Exception
End Try
I'm getting an error that says:
Unable to cast object of type 'System.Data.Linq.DataQuery`1[WhiteWaterPhotos.Photo]' to type 'WhiteWaterPhotos.Photo'.
I have two separate db.SubmitChanges() because when the button is pressed, I have it delete the records from 1 table, and then the next.
I'm lost, can someone help me out?
Hi,
I've used the Simple Promote Plugin in Hudson and it set my build to "keep this build forever".
Is there any way i can delete it?
I got access to the slave who build it and to the master (tried to find anything related in there but no luck).
Thanks,
Tiago
Hi everybody,
My question is quite straightforward. I have a table, with, lets say x rows, with each an id, but i don't know how many rows i have. Now i want to delete the last row of my table for some reason... Is there an easy way to do that in android? I have been trying to use the last_insert_rowid in my where clause...but no luck so far...
any idea?
thx for help
Hello,
Anybody can help me with this mysql query:
delete from generic__campaings_included where dealer_id not in ('2,3,4') and campaing_id = '1'
When i execute this query i didnt get normal result. Exceot 2 (dealer_id) all rows deleted.
How can i use "not in" with "and" operator?
PS. Sorry for my english)
I am programming something like e-mail for my users. I want to allow people to select letters and delete selected. How can I do it? I can't imagine how can I do it only with one MySQL query. Is it even possible?
I need a script to automatically delete the user profile left on ubuntu 9.04, anyone please send me this mail: [email protected] thank you, please indicate how I work not fluent in shellscript.
hi folks,
i have an app in salesforce..but i need a standalone webpage ..so i imported the objects created ..please coulde you give the codes for this three buttons...
add
edit
delete
I am trying to write a batch file that will examine a given directory, read each file for a given string "Example" and then delete any files that contain the string. The files are also System Files so I don't know what the exact extension is or if that matters (maybe you can just omit a file type filter and have it read all files?). Some of the files will be locked from reading as well so it needs to handle access denial errors if that occurs, not sure how batch files handle that.
I am looking for a functor that deletes its argument:
template<class T>
struct delete_functor
{
void operator()(T* p)
{
delete p;
}
};
Is there something like this in std, tr1 or boost?
HI ,
i am having a table like
<table id="toc" class="toc" border="1" summary="Contents">
</table>
i am trying to delete the entire table using javascript.how to do this??
I know you can do bulk XML inserts into SQL Server 2005 tables from your C# code using datasets/datatables.
Is it possible to do the same but as a delete?