Friday, February 24, 2012

How to Delete Files on Maintenance Plan


Hello,

I am creating a Maintenance Plan in SQL Server 2005. The 'Back Up Database Task' has the choice 'Create a sub-directory for each database' as SQL Server 2000 does.

But when I add a 'Maintenance Cleanup Task' I do not see a choice to delete files on subdirectories. Looks like it only deletes the files from the directory I specify. So, looks like SQL Server 2005 is removing some functionality already available in SQL Server 2000. Is there a way to delete those files without needing to specify each directory?

I do not see any documentarion about xp_delete_file either.

Thanks,

Ben Nevarez
I am having the same exact problem. Does anybody have the answer?

Scott Suddarth
|||

I have the same problem, I guess that you still did not find the solution?.

If ever,tell me..

FKy

THX

|||Same problem as well - I also can't find any info on xp_delete_file. Any progress?|||

I have the same problem and found a blog in http://blogs.msdn.com/dditweb/archive/2005/10/18/482478.aspx : "I talked to the SQL team and the response was that it might be a feature added at a later time.".

Additionally, there is a problem with the date format on non-English servers.

I think, SQL Server 2005 should provide a way to delete old backup files in the same simple and robust way as SQL Server 2000.

|||

We are taking this bug seriously and evaluating to get this addressed soon.

The suggested workaround in the blog is recommended, till this one gets addressed.

Thanks,

Gops Dwarak

|||

I would like to hear more feedback on how reasonable is the suggested workaround in the blog. Please share your experience.

Thanks,

Gops Dwarak

|||

The workarounds aren't reasonable. If I go the route of having a cleanup task in a given maintenance plan for each database that I have backing up to its own subfolder, then when I add a database to the system, I have to remember to go add a cleanup task for the new database -- on a server with hundreds of databases and a rather dynamic environment for adding/removing such, that is a nightmare.

This is the single-most obvious headache that I've encountered since upgrading a production SQL Server 2000 database system with just today. While this particular db system is in production, I have a lot of leeway with messing around with it for the next couple of weeks. For my other production SQL 2000 dbs that we'll be upgrading eventually, this issue causes real heartburn, and I'm none-too-happy about the workarounds.

Thanks for listening!

Edit: Well, given the option of putting all of my database backup files in one folder (i.e. for each database), I will say that is an easy workaround. I guess I wouldn't mind it on a server with just a few dbs. But, again, with a server with hundreds of SQL Server databases being backed up, this is non-ideal.

I'd also like to point out that when I upgraded to 2005, I was less than impressed with the migration of my SQL Server 2000 maint plans into 2005 -- they were so screwed up that I ended up just deleting them and recreating new ones within 2005 -- my guess is that lots of people will end up going this route.

|||

My workaround is to use the free GNU UnxUtils (see http://unxutils.sourceforge.net ). I wrote an one-line batch file named delete_old_db_backups.bat to delete all files older than 9 days in the backup directory and all its subdirectories: "C:\scripts\find.exe C:\backup -name *backup* -mtime +9 -exec C:\scripts\rm.exe \"{}\" ;". This batch file is executed by a SQL Agent job, which I defined as the first task of type "Execute SQL Server Agent Job Task" in my maintenance plan. This solution now works fine.

Best regards

Walter

|||

Hi

This workaround is not reasonable. I tried this but no of the BAK files are deleted. I tried to find information about the xp_delete_file procedure , but no chance. Probably there also a problem with the datesettings in my system. OS and SQL server are english, but the standards and format are German (Switzerland)

I'll prefere the same functionality to delete old files like in SQL2000

best reagards

Cougar J

|||

I will echo the sentiments above that this is a major headache. Before reading this thread I had already added tasks to my maintenance plans to delete old backup files from each subdirectory, but that is a real hassle considering one of the primary benefits of maintenance plans is that they are easy to set up.

On a second note, I am apparently experiencing permission problems when my maintenance plan executes xp_Delete_File. Does it run under a separate security context? In this particular maintenance plan, my first task backs up several databases (to subdirectories), and the Maintenance Cleanup Tasks are unable to find the directory specified. There is no reason that it should have problems finding the path to the files from one task to the next.

I actually just got so frustrated debugging the maintenance plan that I wrote a VBscript command to delete the files and created a separate job to run it. It's ironic, because I had avoided maintenance plans for years in Sql2000 and I had decided to give them a shot in Sql2005. At the moment, it is easier for me to go back to my old maintenance scripts.

|||

Thanks for all your feedback , this issue is getting addressed for Service Pack 1.

The cleanup task will have an option to clean up files in subfolders, this option will not be on by default and users can turn on to have the same functionality as SQL2000

Gops Dwarak

|||

Great news that it is being addressed. Now for te next logical question... When should we expect to see SP1? Q3, Q4, sometime in 2007?

Thanks again,
Kevin

|||

Kmartin wrote:

Great news that it is being addressed. Now for te next logical question... When should we expect to see SP1? Q3, Q4, sometime in 2007?

Thanks again,
Kevin

Seconding Kmartin's question - any idea when we might see SP1?

Many thanks,

Megan

|||

I am having a similar issue but I have daily backup files that have the extension of .nb7. When I create a maintenance cleanup task, to delete all nb7 files that are 2 days and older, SQL will not delete these files.

Further, I've created a test Maintenance task with a maintenance cleanup task specifically to delete the .nb7 files that are 1 day or older .When I execute the maintenance task, the files are still present in this directory. I've verified that the SQLServer2005MSSQLUsers$Servername$VVSQL user has full permissions to the directory root directory which is d:\backup\. I've also tried executing this maintenance task with the Everyone Group having full control over the d:\backup\ directory and still no dice. I've tried to change the file extension from .nb7 to nb7 (in the file extension spot) and the files still do not delete.

** I've changed the date between all of these steps and the .nb7 files are older than 1 month.

** I've checked the SQL server agent service credentials and they are set to LocalSystem, and I've verified that the SYSTEM user account has full control over the d:\backup\ directory.

** I've verified that the .nb7 files are NOT in use while this backup is Maintenance Task is being executed.

** I've even tried to trick ol' SQL by renaming the file extensions from .nb7 to .bak. SQL still didn't delete the file.

** The maintenance plan, both the daily and the testing, are being executed under the SA account.

** The maintenance plan is pointing to the correct directory of where the files are stored d:\backup\daily\

** I've turned on auditing of success/failures for all of the audit trials, and nothing critical/warning occur in the event logs for this transaction.

**The maintenance tasks execute successfully.

Finally, being completely irritated by the lack of deletion ability of SQL Server, I pointed the test maintenance task to a bunch of old SQL backup files and executed the script. SUCCESS! This to me implies that SQL can only delete SQL backups and it truly isn't file extension specific?

I could just being losing it, but I could have swore that the I got this working before.

Please verify my findings? (SQL only deletes SQL files)

-Brent

How to Delete Files on Maintenance Plan


Hello,

I am creating a Maintenance Plan in SQL Server 2005. The 'Back Up Database Task' has the choice 'Create a sub-directory for each database' as SQL Server 2000 does.

But when I add a 'Maintenance Cleanup Task' I do not see a choice to delete files on subdirectories. Looks like it only deletes the files from the directory I specify. So, looks like SQL Server 2005 is removing some functionality already available in SQL Server 2000. Is there a way to delete those files without needing to specify each directory?

I do not see any documentarion about xp_delete_file either.

Thanks,

Ben Nevarez
I am having the same exact problem. Does anybody have the answer?

Scott Suddarth
|||

I have the same problem, I guess that you still did not find the solution?.

If ever,tell me..

FKy

THX

|||Same problem as well - I also can't find any info on xp_delete_file. Any progress?|||

I have the same problem and found a blog in http://blogs.msdn.com/dditweb/archive/2005/10/18/482478.aspx : "I talked to the SQL team and the response was that it might be a feature added at a later time.".

Additionally, there is a problem with the date format on non-English servers.

I think, SQL Server 2005 should provide a way to delete old backup files in the same simple and robust way as SQL Server 2000.

|||

We are taking this bug seriously and evaluating to get this addressed soon.

The suggested workaround in the blog is recommended, till this one gets addressed.

Thanks,

Gops Dwarak

|||

I would like to hear more feedback on how reasonable is the suggested workaround in the blog. Please share your experience.

Thanks,

Gops Dwarak

|||

The workarounds aren't reasonable. If I go the route of having a cleanup task in a given maintenance plan for each database that I have backing up to its own subfolder, then when I add a database to the system, I have to remember to go add a cleanup task for the new database -- on a server with hundreds of databases and a rather dynamic environment for adding/removing such, that is a nightmare.

This is the single-most obvious headache that I've encountered since upgrading a production SQL Server 2000 database system with just today. While this particular db system is in production, I have a lot of leeway with messing around with it for the next couple of weeks. For my other production SQL 2000 dbs that we'll be upgrading eventually, this issue causes real heartburn, and I'm none-too-happy about the workarounds.

Thanks for listening!

Edit: Well, given the option of putting all of my database backup files in one folder (i.e. for each database), I will say that is an easy workaround. I guess I wouldn't mind it on a server with just a few dbs. But, again, with a server with hundreds of SQL Server databases being backed up, this is non-ideal.

I'd also like to point out that when I upgraded to 2005, I was less than impressed with the migration of my SQL Server 2000 maint plans into 2005 -- they were so screwed up that I ended up just deleting them and recreating new ones within 2005 -- my guess is that lots of people will end up going this route.

|||

My workaround is to use the free GNU UnxUtils (see http://unxutils.sourceforge.net ). I wrote an one-line batch file named delete_old_db_backups.bat to delete all files older than 9 days in the backup directory and all its subdirectories: "C:\scripts\find.exe C:\backup -name *backup* -mtime +9 -exec C:\scripts\rm.exe \"{}\" ;". This batch file is executed by a SQL Agent job, which I defined as the first task of type "Execute SQL Server Agent Job Task" in my maintenance plan. This solution now works fine.

Best regards

Walter

|||

Hi

This workaround is not reasonable. I tried this but no of the BAK files are deleted. I tried to find information about the xp_delete_file procedure , but no chance. Probably there also a problem with the datesettings in my system. OS and SQL server are english, but the standards and format are German (Switzerland)

I'll prefere the same functionality to delete old files like in SQL2000

best reagards

Cougar J

|||

I will echo the sentiments above that this is a major headache. Before reading this thread I had already added tasks to my maintenance plans to delete old backup files from each subdirectory, but that is a real hassle considering one of the primary benefits of maintenance plans is that they are easy to set up.

On a second note, I am apparently experiencing permission problems when my maintenance plan executes xp_Delete_File. Does it run under a separate security context? In this particular maintenance plan, my first task backs up several databases (to subdirectories), and the Maintenance Cleanup Tasks are unable to find the directory specified. There is no reason that it should have problems finding the path to the files from one task to the next.

I actually just got so frustrated debugging the maintenance plan that I wrote a VBscript command to delete the files and created a separate job to run it. It's ironic, because I had avoided maintenance plans for years in Sql2000 and I had decided to give them a shot in Sql2005. At the moment, it is easier for me to go back to my old maintenance scripts.

|||

Thanks for all your feedback , this issue is getting addressed for Service Pack 1.

The cleanup task will have an option to clean up files in subfolders, this option will not be on by default and users can turn on to have the same functionality as SQL2000

Gops Dwarak

|||

Great news that it is being addressed. Now for te next logical question... When should we expect to see SP1? Q3, Q4, sometime in 2007?

Thanks again,
Kevin

|||

Kmartin wrote:

Great news that it is being addressed. Now for te next logical question... When should we expect to see SP1? Q3, Q4, sometime in 2007?

Thanks again,
Kevin

Seconding Kmartin's question - any idea when we might see SP1?

Many thanks,

Megan

|||

I am having a similar issue but I have daily backup files that have the extension of .nb7. When I create a maintenance cleanup task, to delete all nb7 files that are 2 days and older, SQL will not delete these files.

Further, I've created a test Maintenance task with a maintenance cleanup task specifically to delete the .nb7 files that are 1 day or older .When I execute the maintenance task, the files are still present in this directory. I've verified that the SQLServer2005MSSQLUsers$Servername$VVSQL user has full permissions to the directory root directory which is d:\backup\. I've also tried executing this maintenance task with the Everyone Group having full control over the d:\backup\ directory and still no dice. I've tried to change the file extension from .nb7 to nb7 (in the file extension spot) and the files still do not delete.

** I've changed the date between all of these steps and the .nb7 files are older than 1 month.

** I've checked the SQL server agent service credentials and they are set to LocalSystem, and I've verified that the SYSTEM user account has full control over the d:\backup\ directory.

** I've verified that the .nb7 files are NOT in use while this backup is Maintenance Task is being executed.

** I've even tried to trick ol' SQL by renaming the file extensions from .nb7 to .bak. SQL still didn't delete the file.

** The maintenance plan, both the daily and the testing, are being executed under the SA account.

** The maintenance plan is pointing to the correct directory of where the files are stored d:\backup\daily\

** I've turned on auditing of success/failures for all of the audit trials, and nothing critical/warning occur in the event logs for this transaction.

**The maintenance tasks execute successfully.

Finally, being completely irritated by the lack of deletion ability of SQL Server, I pointed the test maintenance task to a bunch of old SQL backup files and executed the script. SUCCESS! This to me implies that SQL can only delete SQL backups and it truly isn't file extension specific?

I could just being losing it, but I could have swore that the I got this working before.

Please verify my findings? (SQL only deletes SQL files)

-Brent

How to Delete Files on Maintenance Plan


Hello,

I am creating a Maintenance Plan in SQL Server 2005. The 'Back Up Database Task' has the choice 'Create a sub-directory for each database' as SQL Server 2000 does.

But when I add a 'Maintenance Cleanup Task' I do not see a choice to delete files on subdirectories. Looks like it only deletes the files from the directory I specify. So, looks like SQL Server 2005 is removing some functionality already available in SQL Server 2000. Is there a way to delete those files without needing to specify each directory?

I do not see any documentarion about xp_delete_file either.

Thanks,

Ben Nevarez
I am having the same exact problem. Does anybody have the answer?

Scott Suddarth
|||

I have the same problem, I guess that you still did not find the solution?.

If ever,tell me..

FKy

THX

|||Same problem as well - I also can't find any info on xp_delete_file. Any progress?|||

I have the same problem and found a blog in http://blogs.msdn.com/dditweb/archive/2005/10/18/482478.aspx : "I talked to the SQL team and the response was that it might be a feature added at a later time.".

Additionally, there is a problem with the date format on non-English servers.

I think, SQL Server 2005 should provide a way to delete old backup files in the same simple and robust way as SQL Server 2000.

|||

We are taking this bug seriously and evaluating to get this addressed soon.

The suggested workaround in the blog is recommended, till this one gets addressed.

Thanks,

Gops Dwarak

|||

I would like to hear more feedback on how reasonable is the suggested workaround in the blog. Please share your experience.

Thanks,

Gops Dwarak

|||

The workarounds aren't reasonable. If I go the route of having a cleanup task in a given maintenance plan for each database that I have backing up to its own subfolder, then when I add a database to the system, I have to remember to go add a cleanup task for the new database -- on a server with hundreds of databases and a rather dynamic environment for adding/removing such, that is a nightmare.

This is the single-most obvious headache that I've encountered since upgrading a production SQL Server 2000 database system with just today. While this particular db system is in production, I have a lot of leeway with messing around with it for the next couple of weeks. For my other production SQL 2000 dbs that we'll be upgrading eventually, this issue causes real heartburn, and I'm none-too-happy about the workarounds.

Thanks for listening!

Edit: Well, given the option of putting all of my database backup files in one folder (i.e. for each database), I will say that is an easy workaround. I guess I wouldn't mind it on a server with just a few dbs. But, again, with a server with hundreds of SQL Server databases being backed up, this is non-ideal.

I'd also like to point out that when I upgraded to 2005, I was less than impressed with the migration of my SQL Server 2000 maint plans into 2005 -- they were so screwed up that I ended up just deleting them and recreating new ones within 2005 -- my guess is that lots of people will end up going this route.

|||

My workaround is to use the free GNU UnxUtils (see http://unxutils.sourceforge.net ). I wrote an one-line batch file named delete_old_db_backups.bat to delete all files older than 9 days in the backup directory and all its subdirectories: "C:\scripts\find.exe C:\backup -name *backup* -mtime +9 -exec C:\scripts\rm.exe \"{}\" ;". This batch file is executed by a SQL Agent job, which I defined as the first task of type "Execute SQL Server Agent Job Task" in my maintenance plan. This solution now works fine.

Best regards

Walter

|||

Hi

This workaround is not reasonable. I tried this but no of the BAK files are deleted. I tried to find information about the xp_delete_file procedure , but no chance. Probably there also a problem with the datesettings in my system. OS and SQL server are english, but the standards and format are German (Switzerland)

I'll prefere the same functionality to delete old files like in SQL2000

best reagards

Cougar J

|||

I will echo the sentiments above that this is a major headache. Before reading this thread I had already added tasks to my maintenance plans to delete old backup files from each subdirectory, but that is a real hassle considering one of the primary benefits of maintenance plans is that they are easy to set up.

On a second note, I am apparently experiencing permission problems when my maintenance plan executes xp_Delete_File. Does it run under a separate security context? In this particular maintenance plan, my first task backs up several databases (to subdirectories), and the Maintenance Cleanup Tasks are unable to find the directory specified. There is no reason that it should have problems finding the path to the files from one task to the next.

I actually just got so frustrated debugging the maintenance plan that I wrote a VBscript command to delete the files and created a separate job to run it. It's ironic, because I had avoided maintenance plans for years in Sql2000 and I had decided to give them a shot in Sql2005. At the moment, it is easier for me to go back to my old maintenance scripts.

|||

Thanks for all your feedback , this issue is getting addressed for Service Pack 1.

The cleanup task will have an option to clean up files in subfolders, this option will not be on by default and users can turn on to have the same functionality as SQL2000

Gops Dwarak

|||

Great news that it is being addressed. Now for te next logical question... When should we expect to see SP1? Q3, Q4, sometime in 2007?

Thanks again,
Kevin

|||

Kmartin wrote:

Great news that it is being addressed. Now for te next logical question... When should we expect to see SP1? Q3, Q4, sometime in 2007?

Thanks again,
Kevin

Seconding Kmartin's question - any idea when we might see SP1?

Many thanks,

Megan

|||

I am having a similar issue but I have daily backup files that have the extension of .nb7. When I create a maintenance cleanup task, to delete all nb7 files that are 2 days and older, SQL will not delete these files.

Further, I've created a test Maintenance task with a maintenance cleanup task specifically to delete the .nb7 files that are 1 day or older .When I execute the maintenance task, the files are still present in this directory. I've verified that the SQLServer2005MSSQLUsers$Servername$VVSQL user has full permissions to the directory root directory which is d:\backup\. I've also tried executing this maintenance task with the Everyone Group having full control over the d:\backup\ directory and still no dice. I've tried to change the file extension from .nb7 to nb7 (in the file extension spot) and the files still do not delete.

** I've changed the date between all of these steps and the .nb7 files are older than 1 month.

** I've checked the SQL server agent service credentials and they are set to LocalSystem, and I've verified that the SYSTEM user account has full control over the d:\backup\ directory.

** I've verified that the .nb7 files are NOT in use while this backup is Maintenance Task is being executed.

** I've even tried to trick ol' SQL by renaming the file extensions from .nb7 to .bak. SQL still didn't delete the file.

** The maintenance plan, both the daily and the testing, are being executed under the SA account.

** The maintenance plan is pointing to the correct directory of where the files are stored d:\backup\daily\

** I've turned on auditing of success/failures for all of the audit trials, and nothing critical/warning occur in the event logs for this transaction.

**The maintenance tasks execute successfully.

Finally, being completely irritated by the lack of deletion ability of SQL Server, I pointed the test maintenance task to a bunch of old SQL backup files and executed the script. SUCCESS! This to me implies that SQL can only delete SQL backups and it truly isn't file extension specific?

I could just being losing it, but I could have swore that the I got this working before.

Please verify my findings? (SQL only deletes SQL files)

-Brent

How to delete duplicate rows

Hi,
Currently we are having one large table in that we are having more than
1 lacs record but most of the records are duplicates(All columns are having
same values).
How can i delete the particular duplicate row?
Please give me a solution as soon as possible
Thanks,
Herbert
Hi
This script has written by Itzik Ben-Gan
CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"Herbert" <Herbert@.discussions.microsoft.com> wrote in message
news:BE1F27AD-B81D-4CF6-94B7-630BC7979FF0@.microsoft.com...
> Hi,
> Currently we are having one large table in that we are having more
than
> 1 lacs record but most of the records are duplicates(All columns are
having
> same values).
> How can i delete the particular duplicate row?
> Please give me a solution as soon as possible
> Thanks,
> Herbert
|||delete tablename
WHERE (((tablename.dupfield) In (SELECT dupfield FROM tablename As Tmp GROUP
BY dupfield HAVING Count(*)>1 )))
"Herbert" wrote:

> Hi,
> Currently we are having one large table in that we are having more than
> 1 lacs record but most of the records are duplicates(All columns are having
> same values).
> How can i delete the particular duplicate row?
> Please give me a solution as soon as possible
> Thanks,
> Herbert
|||INF: How to Remove Duplicate Rows From a Table
http://support.microsoft.com/default...44&Product=sql
AMB
"Herbert" wrote:

> Hi,
> Currently we are having one large table in that we are having more than
> 1 lacs record but most of the records are duplicates(All columns are having
> same values).
> How can i delete the particular duplicate row?
> Please give me a solution as soon as possible
> Thanks,
> Herbert
|||Hi,
Suppose if the table doesn't have any identity column and all the
remaining columns are equal and i want to have only one row and delete all
duplicate rows.
thanks.,
herbert
"Uri Dimant" wrote:

> Hi
> This script has written by Itzik Ben-Gan
> CREATE TABLE #Demo (
> idNo int identity(1,1),
> colA int,
> colB int
> )
> INSERT INTO #Demo(colA,colB) VALUES (1,6)
> INSERT INTO #Demo(colA,colB) VALUES (1,6)
> INSERT INTO #Demo(colA,colB) VALUES (2,4)
> INSERT INTO #Demo(colA,colB) VALUES (3,3)
> INSERT INTO #Demo(colA,colB) VALUES (4,2)
> INSERT INTO #Demo(colA,colB) VALUES (3,3)
> INSERT INTO #Demo(colA,colB) VALUES (5,1)
> INSERT INTO #Demo(colA,colB) VALUES (8,1)
> PRINT 'Table'
> SELECT * FROM #Demo
> PRINT 'Duplicates in Table'
> SELECT * FROM #Demo
> WHERE idNo IN
> (SELECT B.idNo
> FROM #Demo A JOIN #Demo B
> ON A.idNo <> B.idNo
> AND A.colA = B.colA
> AND A.colB = B.colB)
> PRINT 'Duplicates to Delete'
> SELECT * FROM #Demo
> WHERE idNo IN
> (SELECT B.idNo
> FROM #Demo A JOIN #Demo B
> ON A.idNo < B.idNo -- < this time, not <>
> AND A.colA = B.colA
> AND A.colB = B.colB)
> DELETE FROM #Demo
> WHERE idNo IN
> (SELECT B.idNo
> FROM #Demo A JOIN #Demo B
> ON A.idNo < B.idNo -- < this time, not <>
> AND A.colA = B.colA
> AND A.colB = B.colB)
> PRINT 'Cleaned-up Table'
> SELECT * FROM #Demo
> DROP TABLE #Demo
> "Herbert" <Herbert@.discussions.microsoft.com> wrote in message
> news:BE1F27AD-B81D-4CF6-94B7-630BC7979FF0@.microsoft.com...
> than
> having
>
>

How to delete duplicate rows

Hi,
Currently we are having one large table in that we are having more than
1 lacs record but most of the records are duplicates(All columns are having
same values).
How can i delete the particular duplicate row?
Please give me a solution as soon as possible
Thanks,
HerbertHi
This script has written by Itzik Ben-Gan
CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"Herbert" <Herbert@.discussions.microsoft.com> wrote in message
news:BE1F27AD-B81D-4CF6-94B7-630BC7979FF0@.microsoft.com...
> Hi,
> Currently we are having one large table in that we are having more
than
> 1 lacs record but most of the records are duplicates(All columns are
having
> same values).
> How can i delete the particular duplicate row?
> Please give me a solution as soon as possible
> Thanks,
> Herbert|||delete tablename
WHERE (((tablename.dupfield) In (SELECT dupfield FROM tablename As Tmp GROUP
BY dupfield HAVING Count(*)>1 )))
"Herbert" wrote:

> Hi,
> Currently we are having one large table in that we are having more tha
n
> 1 lacs record but most of the records are duplicates(All columns are havin
g
> same values).
> How can i delete the particular duplicate row?
> Please give me a solution as soon as possible
> Thanks,
> Herbert|||INF: How to Remove Duplicate Rows From a Table
http://support.microsoft.com/defaul...444&Product=sql
AMB
"Herbert" wrote:

> Hi,
> Currently we are having one large table in that we are having more tha
n
> 1 lacs record but most of the records are duplicates(All columns are havin
g
> same values).
> How can i delete the particular duplicate row?
> Please give me a solution as soon as possible
> Thanks,
> Herbert|||Hi,
Suppose if the table doesn't have any identity column and all the
remaining columns are equal and i want to have only one row and delete all
duplicate rows.
thanks.,
herbert
"Uri Dimant" wrote:

> Hi
> This script has written by Itzik Ben-Gan
> CREATE TABLE #Demo (
> idNo int identity(1,1),
> colA int,
> colB int
> )
> INSERT INTO #Demo(colA,colB) VALUES (1,6)
> INSERT INTO #Demo(colA,colB) VALUES (1,6)
> INSERT INTO #Demo(colA,colB) VALUES (2,4)
> INSERT INTO #Demo(colA,colB) VALUES (3,3)
> INSERT INTO #Demo(colA,colB) VALUES (4,2)
> INSERT INTO #Demo(colA,colB) VALUES (3,3)
> INSERT INTO #Demo(colA,colB) VALUES (5,1)
> INSERT INTO #Demo(colA,colB) VALUES (8,1)
> PRINT 'Table'
> SELECT * FROM #Demo
> PRINT 'Duplicates in Table'
> SELECT * FROM #Demo
> WHERE idNo IN
> (SELECT B.idNo
> FROM #Demo A JOIN #Demo B
> ON A.idNo <> B.idNo
> AND A.colA = B.colA
> AND A.colB = B.colB)
> PRINT 'Duplicates to Delete'
> SELECT * FROM #Demo
> WHERE idNo IN
> (SELECT B.idNo
> FROM #Demo A JOIN #Demo B
> ON A.idNo < B.idNo -- < this time, not <>
> AND A.colA = B.colA
> AND A.colB = B.colB)
> DELETE FROM #Demo
> WHERE idNo IN
> (SELECT B.idNo
> FROM #Demo A JOIN #Demo B
> ON A.idNo < B.idNo -- < this time, not <>
> AND A.colA = B.colA
> AND A.colB = B.colB)
> PRINT 'Cleaned-up Table'
> SELECT * FROM #Demo
> DROP TABLE #Demo
> "Herbert" <Herbert@.discussions.microsoft.com> wrote in message
> news:BE1F27AD-B81D-4CF6-94B7-630BC7979FF0@.microsoft.com...
> than
> having
>
>

How to delete duplicate rows

Hi,
Currently we are having one large table in that we are having more than
1 lacs record but most of the records are duplicates(All columns are having
same values).
How can i delete the particular duplicate row?
Please give me a solution as soon as possible
Thanks,
HerbertHi
This script has written by Itzik Ben-Gan
CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"Herbert" <Herbert@.discussions.microsoft.com> wrote in message
news:BE1F27AD-B81D-4CF6-94B7-630BC7979FF0@.microsoft.com...
> Hi,
> Currently we are having one large table in that we are having more
than
> 1 lacs record but most of the records are duplicates(All columns are
having
> same values).
> How can i delete the particular duplicate row?
> Please give me a solution as soon as possible
> Thanks,
> Herbert|||delete tablename
WHERE (((tablename.dupfield) In (SELECT dupfield FROM tablename As Tmp GROUP
BY dupfield HAVING Count(*)>1 )))
"Herbert" wrote:
> Hi,
> Currently we are having one large table in that we are having more than
> 1 lacs record but most of the records are duplicates(All columns are having
> same values).
> How can i delete the particular duplicate row?
> Please give me a solution as soon as possible
> Thanks,
> Herbert|||INF: How to Remove Duplicate Rows From a Table
http://support.microsoft.com/default.aspx?scid=kb;en-us;139444&Product=sql
AMB
"Herbert" wrote:
> Hi,
> Currently we are having one large table in that we are having more than
> 1 lacs record but most of the records are duplicates(All columns are having
> same values).
> How can i delete the particular duplicate row?
> Please give me a solution as soon as possible
> Thanks,
> Herbert|||Hi,
Suppose if the table doesn't have any identity column and all the
remaining columns are equal and i want to have only one row and delete all
duplicate rows.
thanks.,
herbert
"Uri Dimant" wrote:
> Hi
> This script has written by Itzik Ben-Gan
> CREATE TABLE #Demo (
> idNo int identity(1,1),
> colA int,
> colB int
> )
> INSERT INTO #Demo(colA,colB) VALUES (1,6)
> INSERT INTO #Demo(colA,colB) VALUES (1,6)
> INSERT INTO #Demo(colA,colB) VALUES (2,4)
> INSERT INTO #Demo(colA,colB) VALUES (3,3)
> INSERT INTO #Demo(colA,colB) VALUES (4,2)
> INSERT INTO #Demo(colA,colB) VALUES (3,3)
> INSERT INTO #Demo(colA,colB) VALUES (5,1)
> INSERT INTO #Demo(colA,colB) VALUES (8,1)
> PRINT 'Table'
> SELECT * FROM #Demo
> PRINT 'Duplicates in Table'
> SELECT * FROM #Demo
> WHERE idNo IN
> (SELECT B.idNo
> FROM #Demo A JOIN #Demo B
> ON A.idNo <> B.idNo
> AND A.colA = B.colA
> AND A.colB = B.colB)
> PRINT 'Duplicates to Delete'
> SELECT * FROM #Demo
> WHERE idNo IN
> (SELECT B.idNo
> FROM #Demo A JOIN #Demo B
> ON A.idNo < B.idNo -- < this time, not <>
> AND A.colA = B.colA
> AND A.colB = B.colB)
> DELETE FROM #Demo
> WHERE idNo IN
> (SELECT B.idNo
> FROM #Demo A JOIN #Demo B
> ON A.idNo < B.idNo -- < this time, not <>
> AND A.colA = B.colA
> AND A.colB = B.colB)
> PRINT 'Cleaned-up Table'
> SELECT * FROM #Demo
> DROP TABLE #Demo
> "Herbert" <Herbert@.discussions.microsoft.com> wrote in message
> news:BE1F27AD-B81D-4CF6-94B7-630BC7979FF0@.microsoft.com...
> > Hi,
> > Currently we are having one large table in that we are having more
> than
> > 1 lacs record but most of the records are duplicates(All columns are
> having
> > same values).
> > How can i delete the particular duplicate row?
> >
> > Please give me a solution as soon as possible
> >
> > Thanks,
> > Herbert
>
>

How to delete Duplicate records from table

i have table and in that i have number of records which are duplicated.
i want to delete the duplicate records from this table.
pls help me.CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"shiva" <bany.shanker@.gmail.com> wrote in message
news:1133445445.278560.128440@.g14g2000cwa.googlegroups.com...
>i have table and in that i have number of records which are duplicated.
> i want to delete the duplicate records from this table.
> pls help me.
>|||Unfrotunately, I have not found a clean way to do this. Uri's method will
work great, but technically, his table doesn't have duplicate records (as th
e
identity column prevents that).
It you have true duplicates, here's what I do:
1) Create a table containing all the table's fields plus a count field.
CREATE TABLE #xxx
(
Field1 int,
Field2 int,
NumToDelete int
)
2) Select the records which are duplicate:
INSERT INTO #xxx
SELECT *, COUNT(*) - 1
FROM dupedtable
GROUP BY Field1, Field2
HAVING COUNT(*) > 1
3) Either loop or generate a cursor and go through each record in #xxx
perfoming the following (note, if you loop, you'll need an identity column i
n
#xxx)
SET ROWCOUNT @.NumToDelete
DELETE FROM dupedtable
WHERE Field1 = @.Field1 AND Field2 = @.Field2
That's about it.
Marc
"shiva" wrote:

> i have table and in that i have number of records which are duplicated.
> i want to delete the duplicate records from this table.
> pls help me.
>|||Marc L. Allen wrote:
> Unfrotunately, I have not found a clean way to do this. Uri's method will
> work great, but technically, his table doesn't have duplicate records (as
the
> identity column prevents that).
> It you have true duplicates, here's what I do:
> 1) Create a table containing all the table's fields plus a count field.
> CREATE TABLE #xxx
> (
> Field1 int,
> Field2 int,
> NumToDelete int
> )
> 2) Select the records which are duplicate:
> INSERT INTO #xxx
> SELECT *, COUNT(*) - 1
> FROM dupedtable
> GROUP BY Field1, Field2
> HAVING COUNT(*) > 1
> 3) Either loop or generate a cursor and go through each record in #xxx
> perfoming the following (note, if you loop, you'll need an identity column
in
> #xxx)
> SET ROWCOUNT @.NumToDelete
> DELETE FROM dupedtable
> WHERE Field1 = @.Field1 AND Field2 = @.Field2
> That's about it.
> Marc
>
> "shiva" wrote:
>
delete #demo from #demo inner join #Demo d on #demo.idno < d.idno and
#demo.cola = d.cola and #demo.colb = d.colb
Regards|||Here is the process to delete the duplicate records posted some days back by
some body.
1. SELECT * INTO #Temp1 FROM [Table1]
2. TRUNCATE TABLE [Table1]
3. CREATE UNIQUE INDEX [Index1] ON [Table1] (Unique Column Names) WITH
IGNORE_DUP_KEY
4. INSERT INTO [Table1] (Column Names) SELECT (Column Names) FROM [Table1]
5. DROP INDEX [Table1].[Index1]
Note: In 4 th step,it will take the first row in list of duplicates ,rest of
them will be ignored
Thanks
Kumar
"shiva" wrote:

> i have table and in that i have number of records which are duplicated.
> i want to delete the duplicate records from this table.
> pls help me.
>

How to delete duplicate records from a table ?

I uploaded some data about 2 or 3 times and it keep appending it to the
table.

Now I want to keep only first duplicate and delete rest of.

Suppose part number 123 has been added 3 times so I want to keep only 1
record.

ThanksRefer to following url

http://support.microsoft.com/defaul...B;en-us;q139444

--
- Vishal

How to delete duplicate record

I have table by mistake i have lot of duplicate records. How do i delete it
.?
Thanks
Jayhttp://www.aspfaq.com/2431
Then
http://www.aspfaq.com/2509
"Jay Villa" <jayvilla@.community.nospam> wrote in message
news:OFz5HZonFHA.2080@.TK2MSFTNGP14.phx.gbl...
>I have table by mistake i have lot of duplicate records. How do i delete it
>.?
> Thanks
> Jay
>|||Jay,
Could you post the structure of your table. It would be helpful to know the
column names and primary key columns involved.
Thanks,
Frank Castora
"Jay Villa" <jayvilla@.community.nospam> wrote in message
news:OFz5HZonFHA.2080@.TK2MSFTNGP14.phx.gbl...
>I have table by mistake i have lot of duplicate records. How do i delete it
>.?
> Thanks
> Jay
>|||Frank
Table looks like this
cbbdacc_account_id --> PK
cbbdacc_desc
cbbdacc_resp_pidm
cbbdacc_balance
-Jay
"Frank Castora" <fccsql@.hotmail.com> wrote in message
news:%23BFoubonFHA.860@.TK2MSFTNGP12.phx.gbl...
> Jay,
> Could you post the structure of your table. It would be helpful to know
> the column names and primary key columns involved.
> Thanks,
> Frank Castora
> "Jay Villa" <jayvilla@.community.nospam> wrote in message
> news:OFz5HZonFHA.2080@.TK2MSFTNGP14.phx.gbl...
>|||> cbbdacc_account_id --> PK
Is this an IDENTITY column? Do you need to maintain existing values? If
so, how do you decide which ID # you need to keep?

> cbbdacc_desc
> cbbdacc_resp_pidm
> cbbdacc_balance
Is a row considered a "duplicate" when all three of these columns are
identical in the two rows, or some subset?|||I respectfully defer to Aaron, as the articles he pointed you too are quite
sufficient. :)
Thanks,
Frank Castora
"Jay Villa" <jayvilla@.community.nospam> wrote in message
news:%23AN4KionFHA.4056@.TK2MSFTNGP10.phx.gbl...
> Frank
> Table looks like this
> cbbdacc_account_id --> PK
> cbbdacc_desc
> cbbdacc_resp_pidm
> cbbdacc_balance
>
> -Jay
>
> "Frank Castora" <fccsql@.hotmail.com> wrote in message
> news:%23BFoubonFHA.860@.TK2MSFTNGP12.phx.gbl...
>|||Hi Aaron,
You may want to add:
WITH JustDups AS
(
SELECT * FROM T1 AS A
WHERE surkey <
(SELECT MAX(surkey) FROM T1 AS B
WHERE B.wannabekey = A.wannabekey)
)
DELETE FROM JustDups;
:)
--
BG, SQL Server MVP
www.SolidQualityLearning.com
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:%23zpiXaonFHA.1968@.TK2MSFTNGP14.phx.gbl...
> http://www.aspfaq.com/2431
> Then
> http://www.aspfaq.com/2509
>
>
> "Jay Villa" <jayvilla@.community.nospam> wrote in message
> news:OFz5HZonFHA.2080@.TK2MSFTNGP14.phx.gbl...
>

how to delete distributionDB

after i disable replication. the distributionDB is still there.
where i try to delete it . a error message occured as below:
Error 3724: cannot drop the database because it is being used for replication
please help
Cheers
nick
back up your master database. Issue the following query:
UPDATE master..sysdatabases SET category = 0 where name='distribution'
delete the distribution database.
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"Nick" <Nick@.discussions.microsoft.com> wrote in message
news:E112AE00-DABA-4FB1-BE70-0CAA0791D62F@.microsoft.com...
> after i disable replication. the distributionDB is still there.
> where i try to delete it . a error message occured as below:
> Error 3724: cannot drop the database because it is being used for
replication
> please help
> Cheers
> nick
>
|||when i tried to run
UPDATE master..sysdatabases SET category = 0 where name='nickDistribtuion'
i got error as below:
Ad hoc updates to system catalogs are not enabled. The system administrator
must reconfigure SQL Server to allow this.
"Hilary Cotter" wrote:

> back up your master database. Issue the following query:
> UPDATE master..sysdatabases SET category = 0 where name='distribution'
> delete the distribution database.
> --
> Hilary Cotter
> Looking for a SQL Server replication book?
> http://www.nwsu.com/0974973602.html
> Looking for a FAQ on Indexing Services/SQL FTS
> http://www.indexserverfaq.com
> "Nick" <Nick@.discussions.microsoft.com> wrote in message
> news:E112AE00-DABA-4FB1-BE70-0CAA0791D62F@.microsoft.com...
> replication
>
>
|||sp_configure 'allow updates', 1
reconfigure with override
go
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"Nick" <Nick@.discussions.microsoft.com> wrote in message
news:BB79FB0A-8BED-41D9-BE60-E539DCCFD9D7@.microsoft.com...
> when i tried to run
> UPDATE master..sysdatabases SET category = 0 where
name='nickDistribtuion'
> i got error as below:
> Ad hoc updates to system catalogs are not enabled. The system
administrator[vbcol=seagreen]
> must reconfigure SQL Server to allow this.
> "Hilary Cotter" wrote:
|||it works. thanks a lot.
Nick
"Hilary Cotter" wrote:

> sp_configure 'allow updates', 1
> reconfigure with override
> go
> --
> Hilary Cotter
> Looking for a SQL Server replication book?
> http://www.nwsu.com/0974973602.html
> Looking for a FAQ on Indexing Services/SQL FTS
> http://www.indexserverfaq.com
> "Nick" <Nick@.discussions.microsoft.com> wrote in message
> news:BB79FB0A-8BED-41D9-BE60-E539DCCFD9D7@.microsoft.com...
> name='nickDistribtuion'
> administrator
>
>

how to delete distribution database

Hi Friends,
SQL 2000
I resotred a backup of distribution db as d21 and now when I am tryiong to
delete this db , it does not let me to do so, saying , database in
replication.
How can I delete the d21 database ?
The repplication is on and going now.
Thanks,
PatrickHi
Have you run sp_removedbreplication ?
John
"Patrick" wrote:

> Hi Friends,
> SQL 2000
> I resotred a backup of distribution db as d21 and now when I am tryiong to
> delete this db , it does not let me to do so, saying , database in
> replication.
> How can I delete the d21 database ?
> The repplication is on and going now.
>
> Thanks,
> Patrick
>
>|||Yes I did, and stil it doesn't let me to delete the d21 database.
"John Bell" <jbellnewsposts@.h0tmail.com> wrote in message
news:4B80A39F-2A2D-4C5D-B395-1F8925305BC5@.microsoft.com...
> Hi
> Have you run sp_removedbreplication ?
> John
> "Patrick" wrote:
>|||Hi
You may want to look at step 2 in
http://support.microsoft.com/kb/190797/EN-US/
John
"Patrick" wrote:

> Yes I did, and stil it doesn't let me to delete the d21 database.
>
> "John Bell" <jbellnewsposts@.h0tmail.com> wrote in message
> news:4B80A39F-2A2D-4C5D-B395-1F8925305BC5@.microsoft.com...
>
>

How to delete Database engine...

Hi everyone,

i have a small problem , because i installed sql server 2005 mor then once...and i added some new instances everytime cos i couldnt get connected to some of them...

but now that i found out where the problem was, i dont that many instances...only one would be more then enough...so i was wondering...how can i erase basically database engine ? (or better said instance name...i really dont want to uninstall and install everything all over again).

Thnx for ur help.

You can uninstall that particular instance using Add/Remove programs, where you can see list of SQL instances that are installed on your machine.

How to Delete Data when column have depency with other Column?

in Table A Column is

PriKey No Name

1 1 Apple

2 2 Orange

3 3 Juicy

in Table B column is

Prikey ColumnA Price

1 1 10

2 3 2

3 2 5

TableA.Prikey have Depency with TableB.ColumnA

when I am trying to Delete data from Table A , I got error message becaue the depency

how to delete data when there have depency?

I just know when table have trigger , we can disable trigger before delete Data, and enable trigger when data deleted

does there have a way to disable depency and then enable ?

thank you

Hi,

you could programmatically, depends on your business/architecture, delete the dependant rows in the other table. Another approach would be to use "cascading delete" in SQL Server itself.

Grz, Kris.

|||

thank you.. can you please use my example to teach me how to applicate cascading delete?

thank you very much

|||

sorry for asking ..

delete the dependant rows in the other table. (can you please tell me does it mean.. which TAble should I delete first?)

Another approach would be to use "cascading delete" in SQL Server itself.

still can't understand... did you mean? I should delete one onf tables first?

|||

You have to delete from the table that has the FK Dependency i.e. the TableB here.

|||

so.. if I want to delete Table A , I have to delete Table B first?

thank you

|||

jcjcjc:

I just know when table have trigger , we can disable trigger before delete Data, and enable trigger when data deleted

In 99.99999% of all business cases, the scenario you describe would be a horrible, horrible, horrible choice.

In a multi-user environment - where other users are interacting with the table at the same time - disabling the trigger just defeated whatever reason the trigger exists to serve.

If you ever find yourself thinking of disabling a trigger in order to do something, assume it's a terrible idea until proven otherwise.

The only situations I've ever encountered where this is appropriate to do are:

Mass data loads in which the loading program will do whatever the trigger would have done, just more efficiently for mass data loads.|||

sorry I didn't make my question clearly..

why I posted this qustion is... I am doing DTS

the DTS move online data to offline data and delete the data which have been moved to offline

the problem is when I am deleting Table, the column in the Table have depency with a column in other Table

so it can't be deleted..

just wondering how to delete the data when the column have depency with other column?

thank you

|||

I think you have your answer. Please re-read all the replies you got carefully.

|||

jcjcjc:

so.. if I want to delete Table A , I have to delete Table B first?

Yes.

|||

Perhaps I'm wrong, but I don't think anyone actually answered your question. Cascading deletes are established when you create the key relationships and from that point forward, SQL Server does everything for you. A good example is at at the bottom of this article http://www.mssqlcity.com/Articles/General/using_constraints.htm . Using your example:

ALTER TABLE TableB
ADD CONSTRAINT fk_TableA
FOREIGN KEY (PriKey)
REFERENCES TableA (PriKey) ON DELETE CASCADE

What this says, in English, is that whenever you delete a row in TableA, SQL Server will automatically delete any corresponding rows in TableB.

I think this is what you want.

By the way, you don't have to do this through an Alter, I'm pretty sure it can also be done in the CREATE TABLE TableB command, but it makes for a long and confusing CREATE statement. I always see it done using ALTER.

|||

dbland07666:

Perhaps I'm wrong, but I don't think anyone actually answered your question. Cascading deletes are established when you create the key relationships and from that point forward, SQL Server does everything for you. A good example is at at the bottom of this article http://www.mssqlcity.com/Articles/General/using_constraints.htm . Using your example:

ALTER TABLE TableB
ADD CONSTRAINT fk_TableA
FOREIGN KEY (PriKey)
REFERENCES TableA (PriKey) ON DELETE CASCADE

What this says, in English, is that whenever you delete a row in TableA, SQL Server will automatically delete any corresponding rows in TableB.

I think this is what you want.

By the way, you don't have to do this through an Alter, I'm pretty sure it can also be done in the CREATE TABLE TableB command, but it makes for a long and confusing CREATE statement. I always see it done using ALTER.

Cascade Delete is an awesome tool and properly used it will serve you very well. Inappropriately used it can delete an entire database's data.

Whether to use such a constraint on any given foreign key is a business decision - not just a programming one - because of the level of business risk such a constraint can add to the database.

|||

david wendelken:

Whether to use such a constraint on any given foreign key is a business decision - not just a programming one - because of the level of business risk such a constraint can add to the database.

David: I often agree with your posts, but on this one I completely disagreee. Cascading deletes were introducd to put business rules in the database so you don't have to rely on programmers to get it right. There is no danger to them, or at least no danger beyond that which we have by relying on programmers (and probably a lot less danger). I fail to see any danger in the use of cascading deletes

|||

dbland07666:

david wendelken:

Whether to use such a constraint on any given foreign key is a business decision - not just a programming one - because of the level of business risk such a constraint can add to the database.

David: I often agree with your posts, but on this one I completely disagreee. Cascading deletes were introducd to put business rules in the database so you don't have to rely on programmers to get it right. There is no danger to them, or at least no danger beyond that which we have by relying on programmers (and probably a lot less danger). I fail to see any danger in the use of cascading deletes

I agree with your assessment of how useful cascading deletes are. I design them into my databases all the time. But not for each and every foreign key.

For the right ones, and the right ones only. Choosing to put a cascading delete on a foreign key is not a programmer decision. It is a data modeler / business analyst decision. Programmers (unless they are also the data modeler and business analyst for the application :) ) have NO business creating cascade deletes on foreign keys just to simplify their programming job on a particular task.

Sorry I wasn't clear, but that was the reason for my post. Thanks for giving me the heads up that I needed to clarify things. :)


|||

David:

david wendelken:

Choosing to put a cascading delete on a foreign key is not a programmer decision. It is a data modeler / business analyst decision

Totally agree (as I ususally do with your posts)

How to Delete Data on the Subscriber but Maintain It on the Publisher?

Hi,
We're using merge replication between a Sql Server 2000 Publisher and
Subscribers on PocketPCs running Sql Server Ce.
One part of our data sync scheme deals only with newly created data on
the PocketPC. For this we have an upload-only replication that sends
the new data from the device to the Publisher.
Due to storage constraints on the PcketPC, we want to delete the data
from these SQL CE tables after it has been sent to the Publisher, but I
am assuming that if we do so, upon the next replication this data will
then be deleted from the Publisher also.
We want to avoid that from happening - we want to delete the data on
the subscriber after it has been merged, but we also want to maintain
the data on the publisher.
Is there any way that we can delete the data from the subscriber but
still maintain it on the publisher.
Thanks,
JJ
create a sql account which has rights to insert and update, but not delete
on your publisher. Add this to the pal, and use this account in your SQL CE
program in the PublisherLogin parameter.
Now, for the articles which you wish the deletes not to make it to the
publisher, right click on the publication, select publication properties,
and then click on the articles tab. Click on the browse button to the right
of your table names, and select the merging changes tab. Ensure the delete
command is selected.
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
Looking for a FAQ on Indexing Services/SQL FTS
http://www.indexserverfaq.com
"JJ" <jjabour@.gmail.com> wrote in message
news:1127612785.479827.68040@.o13g2000cwo.googlegro ups.com...
> Hi,
> We're using merge replication between a Sql Server 2000 Publisher and
> Subscribers on PocketPCs running Sql Server Ce.
> One part of our data sync scheme deals only with newly created data on
> the PocketPC. For this we have an upload-only replication that sends
> the new data from the device to the Publisher.
> Due to storage constraints on the PcketPC, we want to delete the data
> from these SQL CE tables after it has been sent to the Publisher, but I
> am assuming that if we do so, upon the next replication this data will
> then be deleted from the Publisher also.
> We want to avoid that from happening - we want to delete the data on
> the subscriber after it has been merged, but we also want to maintain
> the data on the publisher.
> Is there any way that we can delete the data from the subscriber but
> still maintain it on the publisher.
> Thanks,
> JJ
>

How to delete data older than X days, without considering time

When running the following SQL statements, I get the same results.
Though I need to count only -30 days. Both statements below also
consider the time of the day as well, which is not desired

DELETE FROM MNT_R
WHERE MNT_R.TIMESTAMP < GETDATE()- 30

DELETE FROM MNT_R
WHERE MNT_R.TIMESTAMP < DATEADD(d, -30, GETDATE())

Here is the format of the values in column
MNT_R.TIMESTAMP
2005-08-09 06:06:44.577
2005-08-09 06:06:46.810
2005-08-09 06:06:49.060

So, since data are inserted into the MNT_R table every few seconds, my
delete statement will delete different number of rows, according to the
time of the day it runs.

Can you please post a SQL query that will not give me this headache?

thanx a lot allHi there,

You have to convert the source column to a non-using time format like
ISO:

DELETE FROM MNT_R
WHERE VARCHAR(10),MNT_R.TIMESTAMP < CONVERT(VARCHAR(10),GETDATE()-
30,112)

HTH, Jens Suessmeyer.|||nai (nioannides@.laiki.com) writes:
> When running the following SQL statements, I get the same results.
> Though I need to count only -30 days. Both statements below also
> consider the time of the day as well, which is not desired
>
> DELETE FROM MNT_R
> WHERE MNT_R.TIMESTAMP < GETDATE()- 30
> DELETE FROM MNT_R
> WHERE MNT_R.TIMESTAMP < DATEADD(d, -30, GETDATE())
>
> Here is the format of the values in column
> MNT_R.TIMESTAMP
> 2005-08-09 06:06:44.577
> 2005-08-09 06:06:46.810
> 2005-08-09 06:06:49.060
> So, since data are inserted into the MNT_R table every few seconds, my
> delete statement will delete different number of rows, according to the
> time of the day it runs.
> Can you please post a SQL query that will not give me this headache?

Instead of getdate() used convert(char(8), getdate(), 112) to strip
of the time portion.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx

How to Delete article in mearge replication

Dear Friends
I want to delete one article from the current Merge
replication i have use the sp_dropmergearticle but it is
comming up with the error that the ARTICLE CAN NOT BE
DROPED AS THE SNAPSHOT OF THE SAME PUBLICATION IS ALREADY
APPLIED.
Please suggest how I can do the same.
Thanks and best regards
Sharad
Kick everyone off your subscribers and publisher. drop the article. Recreate
your subscriptions using the no-sync option.
Run all merge agents.
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
"sharad" <niitmalad@.yahoo.co.in> wrote in message
news:0cea01c4f3f0$9e1da4e0$a601280a@.phx.gbl...
> Dear Friends
> I want to delete one article from the current Merge
> replication i have use the sp_dropmergearticle but it is
> comming up with the error that the ARTICLE CAN NOT BE
> DROPED AS THE SNAPSHOT OF THE SAME PUBLICATION IS ALREADY
> APPLIED.
> Please suggest how I can do the same.
> Thanks and best regards
> Sharad
|||Sharad try with this SP
sp_repldropcolumn
David Barquero
"sharad" <niitmalad@.yahoo.co.in> wrote in message
news:0cea01c4f3f0$9e1da4e0$a601280a@.phx.gbl...
> Dear Friends
> I want to delete one article from the current Merge
> replication i have use the sp_dropmergearticle but it is
> comming up with the error that the ARTICLE CAN NOT BE
> DROPED AS THE SNAPSHOT OF THE SAME PUBLICATION IS ALREADY
> APPLIED.
> Please suggest how I can do the same.
> Thanks and best regards
> Sharad

How to delete and then add to the bottom of the list

Hi,

I have a record in the Database. I want to perform some functions on the record and then place that record at the end of list.

How can I achieve that ??are you trying to do this from a stored proc ? if so you can get the columnvalues into variables and then insert back into the db..

you can also use the "deleted" table to get the values...but there are some limitations i believe...you can check the documentation for using the deleted table..

HTH|||Data in SQL is, by definition, not sorted unless you specify how you want it sorted. So, if you want a record to be at the end of aset of records, you need to specify an ORDER BY that will put it at the end. If you always want the last record modified to be at the end, you might consider adding a LastModified datetime field to the table, putting in an UPDATE trigger that will set that field to the current date/time (calling GetDate will retrieve the current system date/time), and then have and ORDER BY LastModified on your SELECT command.

How to delete an orphaned push subscription

On server1 I created a push subscription to server2. I deleted the
subscription from server1, but server2 still shows it.
I have referred to SQL Server 2000 Books OnLine topics "How to Delete
a Push
Subscription" and "How to Delete a Pull Subscription", but they are of
no help because they only show how to remove it from server1.
Does anyone know how to go about fixing this?
Thanks!
If the database on server2 is not a subscriber to any other publications and
doesn't itself have any publications, then try running
sp_removedbreplication.
HTH,
Paul Ibison

How to delete an Analysis Service DB?

Hi,

when i try do deploy an AS-Projekt, i get follwing error Massage:

Error 1 Errors in the metadata manager. The dimension with ID of 'v Kundeneigenschaft', Name of 'v Kundeneigenschaft' referenced by the 'v Kundeneigenschaft ~MC' cube, does not exist. Errors in the metadata manager. An error occurred when loading the v Kundeneigenschaft ~MC cube, from the file, '\\?\C:\Program Files\Microsoft SQL Server\MSSQL.2\OLAP\Data\Analysis Services Project3.0.db\v Kundeneigenschaft ~MC.3.cub.xml'. 0 0

By the way, the related Cube is not Part of the AS-Projekt i wish to deploy. This Error above occurs on everything i do: Try to delete this Analysis Service Database, ReDeploy another AS-Projekt, Build and Deploy a new projekt and so on...

Cleanup (delete) of C:\Program Files\Microsoft SQL Server\MSSQL.2\OLAP\Data doesn't help, some more error messages appear.

Anybody an idea?

Greetings, Torsten

Make sure you restart your Analysis Server after deleting files from the C:\Program Files\Microsoft SQL Server\MSSQL.2\OLAP\Data folder.

Edward.
--
This posting is provided "AS IS" with no warranties, and confers no rights

|||

Yes, thanks. Thought i've tried that - but it seem that not...

Now it works!

how to delete all the data in the sql server?

Hi,
Is there a way that i can delete all the data from
all the tables in the sql server, i want to remain the
table's structure and user define function and i dun want
to delete the whole database.
Thank you.
regards,
florenceNo command per se. You'd have to execute a DELETE or TRUNCATE TABLE
statement against all tables. Such is easy to generate or automate (using a
cursor), however you have to consider foreign keys so you do it in the right
order. Or you can run the statements several times.
I suggest that you generate script for your DDL. You really should have your
DDL in a script file (or one file per object) anyhow, so you can generate
script, tidy up and comment the script. You can then drop the database and
re-create it from that script file.
--
Tibor Karaszi, SQL Server MVP
Archive at:
http://groups.google.com/groups?oi=djq&as_ugroup=microsoft.public.sqlserver
"florence" <florencelee@.visualsolutions.co.my> wrote in message
news:04c201c3a6ad$d155a5b0$a501280a@.phx.gbl...
> Hi,
> Is there a way that i can delete all the data from
> all the tables in the sql server, i want to remain the
> table's structure and user define function and i dun want
> to delete the whole database.
> Thank you.
> regards,
> florence|||Hi Florence.
You might find it easier to simply script the database schema (including
stored procs, functions etc), using the SQL Enterprise Manager's scripting
tools, then dropping the database & creating an empty one from the script.
The bigger the database, the more effective this approach will be.
Regards,
Greg Linwood
SQL Server MVP
"florence" <florencelee@.visualsolutions.co.my> wrote in message
news:04c201c3a6ad$d155a5b0$a501280a@.phx.gbl...
> Hi,
> Is there a way that i can delete all the data from
> all the tables in the sql server, i want to remain the
> table's structure and user define function and i dun want
> to delete the whole database.
> Thank you.
> regards,
> florence|||Hi,
Execute this command in SQL Analyzer, Replace dbname with your database
name. This commands will delete all the data from all the user tables.
Careful !!! Truncate is not a logged operation, After issuing this command
you will not be able rollback the data.
use dbname
go
declare @.x nvarchar(255)
set @.x=''
select @.x = @.x+' truncate table ' + name
from sysobjects where type='U'
exec sp_executesql @.x
go
Thanks
Hari
MCDBA
"florence" <florencelee@.visualsolutions.co.my> wrote in message
news:04c201c3a6ad$d155a5b0$a501280a@.phx.gbl...
> Hi,
> Is there a way that i can delete all the data from
> all the tables in the sql server, i want to remain the
> table's structure and user define function and i dun want
> to delete the whole database.
> Thank you.
> regards,
> florence|||Truncate table won't work for tables that are referred to by foreign keys.
> Careful !!! Truncate is not a logged operation, After issuing this command
> you will not be able rollback the data.
Truncate table is logged, and can be rolled back:
use tempdb
go
create table t(c1 int identity)
insert t default values
insert t default values
insert t default values
go
select * from t
begin tran
truncate table t
select * from t
rollback
select * from t
--
Tibor Karaszi, SQL Server MVP
Archive at:
http://groups.google.com/groups?oi=djq&as_ugroup=microsoft.public.sqlserver
"Hari Prasad" <hari_prasad_k@.hotmail.com> wrote in message
news:eogxJmtpDHA.2592@.TK2MSFTNGP10.phx.gbl...
> Hi,
> Execute this command in SQL Analyzer, Replace dbname with your database
> name. This commands will delete all the data from all the user tables.
> Careful !!! Truncate is not a logged operation, After issuing this command
> you will not be able rollback the data.
>
> use dbname
> go
> declare @.x nvarchar(255)
> set @.x=''
> select @.x = @.x+' truncate table ' + name
> from sysobjects where type='U'
> exec sp_executesql @.x
> go
> Thanks
> Hari
> MCDBA
>
> "florence" <florencelee@.visualsolutions.co.my> wrote in message
> news:04c201c3a6ad$d155a5b0$a501280a@.phx.gbl...
> > Hi,
> >
> > Is there a way that i can delete all the data from
> > all the tables in the sql server, i want to remain the
> > table's structure and user define function and i dun want
> > to delete the whole database.
> >
> > Thank you.
> >
> > regards,
> >
> > florence
>|||You may want to generate a script to first drop all the foreign keys and
generate another script to then add the foreign keys back. Run the first
script before the TRUNCATE TABLE statements, and then run the second script
afterwards.
Also, I'd probably re-write the script as follows (with some minor changes):
use dbname
go
declare @.x varchar(8000)
set @.x=''
select @.x = @.x+' truncate table ' + QUOTENAME(name) + char(13) + char(10)
from sysobjects where type='U'
exec sp_executesql @.x
go
Note that varchar(8000) still may not be enough.
--
Linchi Shea
linchi_shea@.NOSPAMml.com
"Hari Prasad" <hari_prasad_k@.hotmail.com> wrote in message
news:eogxJmtpDHA.2592@.TK2MSFTNGP10.phx.gbl...
> Hi,
> Execute this command in SQL Analyzer, Replace dbname with your database
> name. This commands will delete all the data from all the user tables.
> Careful !!! Truncate is not a logged operation, After issuing this command
> you will not be able rollback the data.
>
> use dbname
> go
> declare @.x nvarchar(255)
> set @.x=''
> select @.x = @.x+' truncate table ' + name
> from sysobjects where type='U'
> exec sp_executesql @.x
> go
> Thanks
> Hari
> MCDBA
>
> "florence" <florencelee@.visualsolutions.co.my> wrote in message
> news:04c201c3a6ad$d155a5b0$a501280a@.phx.gbl...
> > Hi,
> >
> > Is there a way that i can delete all the data from
> > all the tables in the sql server, i want to remain the
> > table's structure and user define function and i dun want
> > to delete the whole database.
> >
> > Thank you.
> >
> > regards,
> >
> > florence
>|||Thanks a lot Tiber for the information.
I was under the impression that DDL will automatically commit the
transactions.
Thanks
Hari
"Tibor Karaszi" <tibor.please_reply_to_public_forum.karaszi@.cornerstone.se>
wrote in message news:OYvZ3rtpDHA.2188@.TK2MSFTNGP11.phx.gbl...
> Truncate table won't work for tables that are referred to by foreign keys.
>
> > Careful !!! Truncate is not a logged operation, After issuing this
command
> > you will not be able rollback the data.
> Truncate table is logged, and can be rolled back:
> use tempdb
> go
> create table t(c1 int identity)
> insert t default values
> insert t default values
> insert t default values
> go
> select * from t
> begin tran
> truncate table t
> select * from t
> rollback
> select * from t
> --
> Tibor Karaszi, SQL Server MVP
> Archive at:
>
http://groups.google.com/groups?oi=djq&as_ugroup=microsoft.public.sqlserver
>
> "Hari Prasad" <hari_prasad_k@.hotmail.com> wrote in message
> news:eogxJmtpDHA.2592@.TK2MSFTNGP10.phx.gbl...
> > Hi,
> >
> > Execute this command in SQL Analyzer, Replace dbname with your database
> > name. This commands will delete all the data from all the user tables.
> >
> > Careful !!! Truncate is not a logged operation, After issuing this
command
> > you will not be able rollback the data.
> >
> >
> > use dbname
> > go
> > declare @.x nvarchar(255)
> > set @.x=''
> > select @.x = @.x+' truncate table ' + name
> > from sysobjects where type='U'
> > exec sp_executesql @.x
> > go
> >
> > Thanks
> > Hari
> > MCDBA
> >
> >
> >
> > "florence" <florencelee@.visualsolutions.co.my> wrote in message
> > news:04c201c3a6ad$d155a5b0$a501280a@.phx.gbl...
> > > Hi,
> > >
> > > Is there a way that i can delete all the data from
> > > all the tables in the sql server, i want to remain the
> > > table's structure and user define function and i dun want
> > > to delete the whole database.
> > >
> > > Thank you.
> > >
> > > regards,
> > >
> > > florence
> >
> >
>

How To Delete All Tables (the devils work)

dont open the "How To Delete All Tables" post
it's view count is 666
I guess the devil really is in the detailsInstead, open this one so you can ponder the possibilities.|||i was thinking about dante's divine comedy when i wrote this and thought that it was interesting to think of one of the ironic tortures that the satan is supposed to come up with so you can be punished for all eternity based on your worst fears etc...

so i thought...what would be the worst ironic punishment that the devil could come up with

any suggestions?|||I would be doomed to designing Crystal Reports for all eternity.|||And if you are going to get superstitious, we'll have to start cutting all threads before post #13.

Actually, that may not be a bad idea...|||i dont consider the devil a superstition, more of a boogeyman

here is my torture

i'm trapped in a server room with a monochrome (green) monitor with oracle version 7 trying to write correlated subqueries in the sql*Plus and my keyboard is missing an "L" key and the insert key is locked on!|||Originally posted by Ruprect
i dont consider the devil a superstition, more of a boogeyman

here is my torture

i'm trapped in a server room with a monochrome (green) monitor with oracle version 7 trying to write correlated subqueries in the sql*Plus and my keyboard is missing an "L" key and the insert key is locked on!

working on MS Windows with a keyboard missing the CTRL,ALT & DEL keys ...|||Yeah
coding in the query analyzer while the server is set to the japanese code page in a locked room with rdjabarov and blindman. :p

it's just a joke, just a joke...|||See you in hell, Ruprect! :mad:|||what makes you think that we arent already there?|||Well ... I am sure I am not there ... me and brett are in heaven enjoying the Margaritas and Whiskeys ...

Though we make an occasional trip there ... I sure am not living in Hell|||I don't think I would be allowed to drink a cold beer in Hell, and yet I am.|||Originally posted by blindman
I don't think I would be allowed to drink a cold beer in Hell, and yet I am.

Sunday and you guys are posting...geez...I thought I had an addiction...

Oh, That's right...it's the other thing...

And I bet Nigel would disagree...and it's not fizzy...

And Cursors are useful if you don't know sql...

DTS can be used the same way..

AND Beer is not cold and is not fizzy...

http://www.sqlteam.com/forums/pop_profile.asp?mode=display&id=1578|||Originally posted by Enigma
Well ... I am sure I am not there ... me and brett are in heaven enjoying the Margaritas and Whiskeys ...

Though we make an occasional trip there ... I sure am not living in Hell

Yeah?

Where are all the virgins?|||Now that you talk about it ... havent seen any ...

Am I right about our location ... or are we somewhere else ...|||I think only Muslims get the virgins. Sorry, Brett.|||I don't think I would be allowed to drink a cold beer in Hell, and yet I am.

yes you would
if it was flat or non-alcoholic|||You could always wake up from a hangover, open your eyes with great difficulty, and see me sitting in a chair watching you, smiling, chipper, and ready to chat. I used to do that to my room-mate in college.

The first weekend that his folks showed up (from about four hours drive away) and asked if he lived there, we shouted down from the roof that they should leave him on the porch. We figured that somebody's parents had found him in a frat (or sorority) and were bringing him home. I didn't find out until about a year later that this was an old joke, and that his parents thought we were kidding them (ok, so I was a sheltered kid).

By the time I went to college I had a pretty good background in pharmacology. Most of which I knew from practical experience (I wasn't the healthiest critter on the planet). I didn't have any clue about the recreational possibilities until I met some of the enterprising young folks in the dorms!

-PatP|||Dude, what brought about THAT confessional?|||Originally posted by blindman
Dude, what brought about THAT confessional? Wasn't the original point of this thread to propose awful fates? Can you imagine something worse that being massively hung over, and waking up to find some bright young bozo sitting chipper on a chair, just waiting for someone to talk to ?

-PatP|||Originally posted by Pat Phelan
Wasn't the original point of this thread to propose awful fates? Can you imagine something worse that being massively hung over, and waking up to find some bright young bozo sitting chipper on a chair, just waiting for someone to talk to ?

-PatP

Pretty much sums it up....|||Originally posted by blindman
I think only Muslims get the virgins. Sorry, Brett.

Auch! .. That hurts ..
yep .. I am Muslim .. and I have been trying to explain the real Islam (not the one hijacked since 9/11) to my friends here in the States .. being a mulsim in the states .. has been real tough since then ..

Religion in SQL Server forum ?!? .. I know what some folks are thinking ..

Sorry blindman! I couldn't resist to answer ..

To go back to the original subject of this thread .. my nightmare would be to be trapped in a room with three fanatics (a Muslim developer, a Jewish DBA and a Christian Project Manager) debating who is resposible for the software crash !!!!!! and who is to blame for killing Jesus :o) ..|||Salam!

"a Muslim developer, a Jewish DBA and a Christian Project Manager"

Shoot, I know I've heard that joke before, but I can't remember the punchline. They walk into a bar, right? Or are they in an airplane with only two parachutes? Wait! Wait! They're playing golf...|||okay
i didnt think that this was going to spark a spanish inquisition.
after all, nobody expects a spanish inquisition.

my intent was to have people post ironical examples of dba punishment as if they had gone to hell as illustrated in dante's divine comedy(in this story dante is shown hell and sees that the devil chooses punishments that fit your greatest transgressions. )

like in little nicky when lovitz pretends to be a bird while peeping in a bedroom window. so when he dies, the devil has a giant "horny bird" try to bugger him all throughout eternity.

i re formatted your joke. (joke-92 syntax)

"a Muslim developer, a Jewish DBA and a Christian Project Manager walk into a bar. the bartender looks up and says " hey. what is this, some kind of joke?"|||That was a good one, Scott, and a quick one too!|||Originally posted by Ruprect
my intent was to have people post ironical examples of dba punishment as if they had gone to hell as illustrated in dante's divine comedy(in this story dante is shown hell and sees that the devil chooses punishments that fit your greatest transgressions. ) Ok, how about being the Data Modeler / DBA for a group of developers new to working in the client/server environment. 1/4 of the developers from an ISAM background, 1/4 from an Oracle shop, and 1/2 straight out of class. Have them speak four different native languages, non of which are your native language. Distribute them roughly evenly around the globe, to provide you with 24 hour per day activity.

Then just for good measure, tackle a project for which you are chronically under staffed.

Is that something more like what you'd been expecting ?

-PatP|||Sounds like what we have here, except none of them have designed anything serious, and the majority can't even design pubs without cheating ;)|||Originally posted by Pat Phelan
Ok, how about being the Data Modeler / DBA for a group of developers new to working in the client/server environment. 1/4 of the developers from an ISAM background, 1/4 from an Oracle shop, and 1/2 straight out of class. Have them speak four different native languages, non of which are your native language. Distribute them roughly evenly around the globe, to provide you with 24 hour per day activity.

Then just for good measure, tackle a project for which you are chronically under staffed.

Is that something more like what you'd been expecting ?

-PatP

that's exactly it
except you forgot to mention the deadline.|||Wait. Are we describing ironic punishments, or where we work? ;-)|||if you can find a distinction i would really like to know it.

by the way everyone, i work in sheer hell and am hereby announcing my free-agent status. as soon as i find a new gig i am outa there.|||Mr. Crowley, what went on in your head

How To Delete All Tables

Hi All,
How can i delete all the tables in a DATABASE with a single shot!!
Thanx in advanceWell...what i do is:) may not be the right way:))

Just delete the database......and create a new database......else it will start asking for so many dependencies:))

cheers!


Originally posted by Saravanan.R
Hi All,

How can i delete all the tables in a DATABASE with a single shot!!

Thanx in advance|||Benny,

In a database TABLES, VIEWS, FUNCTIONS, PROCEDURES, TRIGGERS, etc. are there! So I have to delete only TABLES. If I drop the database means I want to recreated all those objects.

I need to delete TABLES alone.

Thanx in advance|||another simple way

generate SQL script of the database, select "all tables", select "generate drop command for each object" check box only (not the create one). you should have a script with all drop commands. run it|||Hi

Its not a appropriate way to drop! plz..|||DELETE FROM sysobjects WHERE xtype='U'
Need to check the option "update system catalogs" for the server properties prior to execute the statement.|||Originally posted by Saravanan.R
Hi All,

How can i delete all the tables in a DATABASE with a single shot!!

Thanx in advance

DO NOT delete anything from sysobjects. That's insane.

If you want to delete the tables (in SQL Server lingo, this just means delete the data out of all of them).

DECLARE
@.sql VARCHAR(4000),
@.int_counter INT,
@.int_max INT

DECLARE @.tables TABLE(
ident INT IDENTITY(1,1) PRIMARY KEY,
table VARCHAR(256))

INSERT @.tables(table)
SELECT name FROM sysobjects WHERE xtype = 'U'

SELECT
@.int_counter = 1,
@.int_max = (SELECT MAX(ident) FROM @.tables))

WHILE @.int_counter <= @.int_max
BEGIN

SELECT @.sql = 'DELETE ' + table
FROM @.tables WHERE ident = @.int_counter

SELECT @.int_counter = @.int_counter + 1
END

This will only work if you don't have foreign keys though, so you would have to make a similar procedure to drop and recreate those. You can find one on SQLServerCentral.com though.

If you really want to just drop all the tables, change the DELETE to DROP TABLE, and you are good to go. NEVER edit the system tables as a shortcut. It's dangerous; and there are too many good scripts someone else has already written to be doing that.|||"Its not a appropriate way to drop!"???

What they heck WOULD be an appropriate way to drop all the tables in a database with dependent procedures, views, functions, and perhaps even triggers?

I have trouble believing what you are doing is appropriate or necessary in the first place!|||Originally posted by blindman
"Its not a appropriate way to drop!"???

What they heck WOULD be an appropriate way to drop all the tables in a database with dependent procedures, views, functions, and perhaps even triggers?

I have trouble believing what you are doing is appropriate or necessary in the first place!

If he's dropping the tables to just recreate them, the biggest problem will be the foreign keys if he has them.|||He is just askin to delete ALL tables. Why r u scared of the foreign keys, obviously he would have the script for recreating the tables which would include the relationships too.|||Again, What For?

If he can run a script to restore them, presumably he could run upalsen's script solution to drop them...|||He says that he wanna delete all tables in one shot, just for fun i guess, therefore one delete query in sysobjects would satiate his desires rather to select all tables and then choosing include drop tables statement and then running the drop table commands for each table.
However, it's clear that playin with system catalogs is not so wise. U r right indeed.|||Saravanan.R

why do you want to do this
it may be that we may have an alternate solution for your problem other than deleting all of your tables

for example if you want to just remove all of the data from your tables without dropping them, then try the truncate table statement.

[Books Online] Truncate Table

ps if you ever directly modify a system table, we will run you out of town and burn your castle like a group of villagers chasing the frankestein monter|||Hi All,

Sorry I have to DELETE (DROP ALL TABLES) in a single shot!|||You think he wants to drop all the tables in his database "just for fun"?

What the heck are YOUR hobbies?|||You can drop all the tables in various different ways. The solution that is right depends on what you are trying to achieve by dropping the tables.

What is it you are trying to achieve? And please don't say "I have to DELETE (DROP ALL TABLES) in a single shot!", we want to know why...|||Sorry Blindman,

After migrating the Oracle to SQLServer I have to compile the SQLServer Objects in a Database. While compiling the Object I will shows error! bec' already Objects were created! Instead of that, before compiling it I want to DROP ALL TABLES. I have thousands of table in my DATABASE. SO I need this statement IF POSSIBLE!. I don't want to DROP THE DATABASE , Thats why am put Q in forums is there any anternate way to DROP TABLES.?

Its not a hobby to post question in FORUMS like this! Sorry Blindman!!.|||Ok, i think there could be some scenarios where one may need to use system-catalogs, e.g, if i need to drop the tables in a DB with names DELETED at the end and i've more that hunderds of table in the database.
What would i do according to derrickleggett's wise advise that i would go to enterprise-manager, make a script of creation and deletion of these tables by looking at each table and marking only the DELETED tables to be included in the script, right. After spending a lot of time i would create the script and then go to query-analyzer and run the DROP TABLES section for these tables. How safe is it, but took very much time, right?
But if i know what i wanna do, i would rather choose:
DELETE FROM sysobjects WHERE name like '%DELETED' AND xtype='U'

It would delete the tables in ONE SHOT in few seconds.
As mentioned; although it's not a good technique to play with sys-catalogs but sometimes there's no other way out.
Now one can comment that why do i need to delete all the DELETED tables in ONE SHOT:D

Howdy!!|||You can always experiment with sp_msforeachtable, but really, you NEED a script that clears the database. In fact, if this is "your baby" you need a good dozen or two of db maintenance scripts, including dropping, creating, etc. You have to be a lazy DBA to have good stuff for everything, but you can't be "that" lazy...|||OK, I guess I understand why you want to do this (thousands of tables? That's a whole other problem...). But why must it be a single statement? I don't see anything in your requirement that prevents you from running multiple statements that load a list of tables into temporary storage and then loops through issueing dynamic DROP statements. This would seem to be what you want, but might require a half-dozen different statements to set up the temporary table(s), populate them, and then run your DROP loop.|||Actually the problem is:
Saravanan.R wants it in ONE SHOT. That's it.:o|||If that was the case, upalsen's script solution would work fine. It may be a long script, but it would be executed "in one shot". :o :rolleyes:|||Hmmm, I want a house and a boat in Dominican Republic...Anyone has a script so that I can get it "IN ONE SHOT"??!!

Also, if DRI is present, along with a script that generates DROPs for tables Saravanan.R will have to handle removing FK constraints.

Here's how I'd do it:

- Create a view using the following code:

create view dbo.vw_DropTables (stmt) as
select
'alter table ' + object_name(id) + ' drop constraint ' +
object_name(constid) + char(13)+char(10)+
"if @.@.error != 0 raiserror ('Failed to drop " +
object_name(constid) + " constraint!', 15, 1)"+
char(13)+char(10)+'go'
from sysconstraints where objectproperty(constid, 'IsForeignKey') = 1
union
select 'drop table ' + name + char(13)+char(10)+
"if @.@.error != 0 raiserror ('Failed to drop " +
object_name(id) + " table!', 15, 1)"+
char(13)+char(10)+'go'
from sysobjects where objectproperty(id, 'IsMSShipped') = 0
and objectproperty(id, 'IsTable') = 1
go

- Create a batch file with the following commands:

bcp <your_db_name>.dbo.vw_DropTables out DropTables.SQL
-S <your_server_name> -T -c
if not exist DropTables.SQL goto ErrorHandler
osql -S <your_server_name> -E -Q"DropTables.SQL" -b
if errorlevel 1 goto ErrorHandler
exit

ErrorHandler:
echo ERROR!|||insert into AccountBalances (AccountHolder, Balance)
select 'rdjabarov', sum('Balance')
from AccountBalances

You owe me a maragarita.|||Mr. Lindman,

I didn't quite get your reply. But that may be the language barrier, huh?!

...And your query will bomb:

Server: Msg 409, Level 16, State 2, Line 1
The sum or average aggregate operation cannot take a varchar data type as an argument.

You owe me a maragarita.
Never heard of such drink...Is it popular in OH?|||This script will work also:

DECLARE
@.int_counter INT,
@.int_max INT,
@.txt_type CHAR(1),
@.txt_object VARCHAR(256),
@.txt_object_parent VARCHAR(256),
@.txt_sql VARCHAR(4000)

DECLARE @.objects TABLE(
ident INT IDENTITY(1,1) PRIMARY KEY,
object VARCHAR(256),
object_parent VARCHAR(256),
object_type CHAR(1))

INSERT @.objects(
object,
object_parent,
object_type)

SELECT CONSTRAINT_NAME, TABLE_NAME, 'C'
FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
UNION ALL
SELECT name, '','U'
FROM sysobjects
WHERE
xtype = 'U'
AND name NOT LIKE 'dt_%'

SELECT
@.int_counter = 1,
@.int_max = (SELECT MAX(ident) FROM @.objects)

WHILE @.int_counter <= @.int_max
BEGIN

SELECT
@.txt_type = o.object_type,
@.txt_object = o.object,
@.txt_object_parent = o.object_parent
FROM
@.objects o
WHERE
o.ident = @.int_counter

IF @.txt_type = 'C'
BEGIN
SELECT @.txt_sql = 'ALTER TABLE ' + @.txt_object_parent + ' DROP CONSTRAINT ' + @.txt_object
END
ELSE
BEGIN
SELECT @.txt_sql = 'DROP TABLE ' + @.txt_object
END

PRINT @.txt_sql

SELECT @.int_counter = @.int_counter + 1
END

and, Talat this isn't a wrestling match to show who's the most manly man in the room. It's just a forum to help people. If you delete all the tables from sysobjects, you just messed up the entire database. You didn't do anything in one shot except shoot yourself in the head.

People should rarely mess with the system catalog, especially not in your case when it's obvious you have no idea how they work. Do you have any useful script to post?|||Good lord, I even had syntax errors in my drink order.

Bartender, call a cab to drive me home.|||use DominicanRepublic
go
exec sp_changeobjectowner 'house', 'rdjabarov'
go
exec sp_changeobjectowner 'boat', 'rdjabarov'
go|||Hi All,

DROP TABLE works with " derrickleggett " solution.

Thanx to all.|||Good for you! Why don't you hire him? He'll provide you with solutions!|||You don't have to hire me. Just send me a check.|||I wouldn't. At a minimum your script will drop dtproperties, and the result still needs to be dealt with (copy/paste into another script). And what's up with looping? Didn't you see BCP...OUT posted earlier?|||I'm just amused by the idea of India outsourcing to Kansas City, MO.|||Originally posted by rdjabarov
I wouldn't. At a minimum your script will drop dtproperties, and the result still needs to be dealt with (copy/paste into another script). And what's up with looping? Didn't you see BCP...OUT posted earlier?

Yeah, that's because I typed AND name NOT LIKE 'dt_%' instead of AND name NOT LIKE 'dt%'. You could have just said that instead.

Also, if you change the PRINT @.txt_sql to EXEC(@.txt_sql) it will run it instead of printing it. I figured most people would figure that out.

How can i delete all the tables in a DATABASE with a single shot!!
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
That's the original post and all he's really trying to do.

The looping loops through those @.txt_sql statements and either prints them off or executes them one by one. It starts at 1 and goes until it gets to the end. It does this by using WHILE and incrementing a counter variable.|||If his company hires the smart chap, this fellow will be fired:)|||Hi derrickleggett,

Yah! In the place of PRINT I replaced the EXEC Statement to EXECUTE that. It works perfectly.

I think that, We can use to DELETE all PROCEDURE instead of putting 'P' for 'U'.|||Yeah, if you want to do that though, just edit it to except an object type, so you can pass in the object type to it.|||Hi,

I have modified to DELETE all the PROCEDURES, VIEWS & now am trying to do function too.|||Originally posted by Saravanan.R
Hi,

I have modified to DELETE all the PROCEDURES, VIEWS & now am trying to do function too.

WHERE xtype IN ('IF','FN','TF')

Why not just drop the whole database. lol|||...or reformat the drive. That's an easy way to drop all tables, procedures, views, and functions in all databases IN ONE SHOT!|||Hi Blindman,

have u forgot the article that i was posted on 04-05-04 10:58 !!!!!!!???

Plz read the article i was posted on 04-05-04 10:58

Thanx for all|||Hey ... just tell us what the hell are you trying to do ... we all are pretty confused ...|||Hi All,

I want to Drop Tables, Procedures, Views ... Because

after migrating the Oracle to SQLServer I have to compile the SQLServer Objects in a particular Database(Eg.sample). While compiling the Objects, if already Objects were exists! I will shows the error! For this I want to drop objects in my DATABASE.

have u got it!!!|||I still don't get it ...

I think I am getting more confused with the terminology you are using ... can you explain it in simpler words ??|||Originally posted by derrickleggett
Yeah, that's because I typed AND name NOT LIKE 'dt_%' instead of AND name NOT LIKE 'dt%'. You could have just said that instead.

Also, if you change the PRINT @.txt_sql to EXEC(@.txt_sql) it will run it instead of printing it. I figured most people would figure that out.

How can i delete all the tables in a DATABASE with a single shot!!
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
That's the original post and all he's really trying to do.

The looping loops through those @.txt_sql statements and either prints them off or executes them one by one. It starts at 1 and goes until it gets to the end. It does this by using WHILE and incrementing a counter variable. Hey, I understand your code, no need to explain what WHILE loop does and what it starts with ;) I don't think you understood mine though! But hey, I've done your loops and got away from it, because there are more elegant ways to do it.

And I do agree with others who question this "DROP IN ONE SHOT" thing. I assume he has the schema script as well, the one that does the reverse, - CREATE ALL OBJECTS IN ONE SHOT...Can you do that? I can ;) But having this knowledge completely dismisses the DROP-ALL approach as absolutely inadequate, regardless of what you're moving your database from, - Oracle, Horacle, Shmoracle, and everything else :D|||Originally posted by Enigma
I still don't get it ...

I think I am getting more confused with the terminology you are using ... can you explain it in simpler words ??

It sounds like part of his import process is validating the actual compiling of objects as a validation process. This actually makes quite a bit of sense.

For instance, if I want to import one subject area at a time, I test the import of those pieces in stages. The first step is to go to my sample database and delete those objects if they exist from a previous test. I only wan to delete the objects I'm testing and don't want to recreate the database.

I then test the compiling of those objects. I then test the import of the data. After the tests validate my process, I run it on the server I'm importing to.

I'm not sure if this is exactly what he's doing, but I could understand why he would want to do it after doing data conversion for so many years. The more validation you have the better.|||Originally posted by blindman
...or reformat the drive. That's an easy way to drop all tables, procedures, views, and functions in all databases IN ONE SHOT!

DELETE * FROM sysdatabases.
It's more easy!!!!!!!:p|||Talat, if you ever come near my server room I will have you arrested. lol|||Hi Enigma,

I have more than 500tables, procedures .. in my SQLServer DATABASE ( Example: saravanan). I have to fix error in my SQL-Server Tables, Transaction SQL Codes afte migrating Oracle to SQLServer. While compiling SQLServer Tables, Procedure.. On that time If the tables, procedures already created in my SARAVANAN database. It will show errors like this " There is already an object named 'TEMPFUNC' in the database. "

For this purpose I have to drop all the tables , procedures before my compilation.|||Anbody know where I can get my Shmoracle certification? I hear it's pretty tough.|||Which track u r interested in, sir, i complted OCP-Developer a few months back and pursuing DBA track now. Both r rather easy. I'm gonna give 70-228 on 20th of April, wish me good luck plz u all, especially Sarvanan!!|||Hi TALAT,

DO THE BEST.

Luv
Saravanan.R|||Originally posted by blindman
Anbody know where I can get my Shmoracle certification? I hear it's pretty tough. I am developing a class for Horacle now. Hoping to complete it by this weekend and start with Shmoracle one.|||Saravanan, I still think you may be going about this in the wrong way. If you are getting errors saying a particular object already exists when you run your script, then your script should either:

1) Drop each object before attempting to create it.
or B) Check to see whether the object already exists before attempting to create it.

Dropping all the objects is a rather blunt instrument for the operation, IMHO.|||Lindman does objects...|||Originally posted by blindman
Saravanan, I still think you may be going about this in the wrong way. If you are getting errors saying a particular object already exists when you run your script, then your script should either:

1) Drop each object before attempting to create it.
or B) Check to see whether the object already exists before attempting to create it.

Dropping all the objects is a rather blunt instrument for the operation, IMHO. ...and finally III) Check to see if object exists. If it does, - drop it. And then create it or whatever other sick things you have in mind ;)
D) Do a separate script that has to be based on dependency between objects. Another way of going about doing it is either dropping FK constraints or disabling them. But either way, you need to do it in a thorough, consistent, and error-preventive way, not in a "ONE SHOT" fashion.|||rdjabarov does posts|||Robert does posts!|||yes ofcourse i do.

Thanx all.