sql server: delete all the rows of all the tables - sql

I'd like to clear the database altogether and reset the data. What's the quickest way to do that? Or, what's the command that will delete all the rows of a table (and I'll repeat that process for all tables)?
Thanks

This approach will enable you to delete content from all tables, even those referenced by a foreign key constraint. You can enhance it to make it check for the absence of foreign key constraints and do a TRUNCATE TABLE in those cases.
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_msforeachtable 'DELETE FROM ?'
EXEC sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL'

If you don't want to script and drop the tables, there are a number of ways to do this with a loop. Here's probably the easiest:
sp_MsForEachTable 'TRUNCATE TABLE ?'

Drop the database and recreate it.

Use SQL Server Management Studio to script the DROP and CREATE statements for the tables and then run the script. Right click on the database and select Tasks --> Generate Scripts. Run through the wizard (make sure to check the Script Drop option on the "Choose Script Options" step) and select all of the tables. The script that is generated should drop all the tables and then recreate them.

Related

ALTER COLUMN WITHOUT DROP

I want to alter column within the table to be NULL from NOT NULL.
The problem is that table has one constraint, one trigger and 4 indexes.
Can I somehow alter that column without dropping and recreating everything?
exec sys.sp_depends 'object_name'
List all dependencies and then drop them an recreate everything.
SQL Managements studio offer option with SCRIPT AS CREATE and you can save all views, triggers, tables as backup...

Copy data only between two databases

Im trying to copy data only between two SQL server 2008 databases. I need to keep the existing stored procs and functions intact and copy data only. The DB schemas are identical but im running into issues with PK's.
I first tried:
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
To remove all data. But get
Failure inserting into the read-only column
So i then tried to set IDENTITY_INSERT ON across all tables with:
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
EXEC sp_MSForEachTable 'ALTER TABLE ? SET IDENTITY_INSERT ON'
with no luck.
What is the best way to export data only between two databases, leaving the original procs and functions intact?
Thanks.
Edit: Im using SQL Export to copy the data from source to destination. I need to keep the destinations DBs procs and functions, just copy the data only.
Just remove the identity specification from all the table pkeys in the second db.
What is likely happening here is that you have pkey as an identity column in both dbs, and it makes sense to do so in the first, but you cant copy its value into another identity column.
You wouldn't want the pkey as an identity pkey in the second db anyway, then, all your foreign keys wouldn't work.
I would probably approach it from a different angle: by scripting all objects via SQL Enterprise Manager into a file and running this file on a blank database. This way, you'll have all metadata but no actual data in the second database, and you can use it for additional copies in the future.
The error you are getting doesn't seems like a PK violation or an Identity issue. I see two possible causes:
If you are getting the error when trying to insert the data, I would check if the tables have any computed columns. Many programs fail to take them into account when exporting data, and include the computed columns in the insert column list.
If you are getting that error in the delete step, probably you have a trigger that fires on delete, and it try to insert data and fails for some reason (the idea of these triggers is maintain a copy of the deleted data in another location). If that is the case, fix the insert or just disable the trigger.
I went with a varation of both answers this in the end. I used a 3rd database as a temp database.
1)I did a full back up of the database i needed the data from (live)
2)I restored this backup to my temp database.
3)I scripted the database i needed the procs and functions from, only scripting procs and funcs and using DROP and IF INCLUDES.
4)I ran the script from #3 against my temp database giving the data from DB1 and the procs and funcs from DB2
5)I restored DB2, using OVERWRITE from a backup of my temp database.
Thanks guys id mark all as correct if I could.
Hi in order to get around your issues with your constraints, please read this blog post I wrote on the subject.
http://tenbulls.co.uk/2009/07/22/checking-your-constraints-to-check-your-integrity/

Disable Primary Key and Re-Enable After SQL Bulk Insert

I am about to run a massive data insert into my DB. I have managed to work out how to enable and rebuild non-clustered indexes on my tables but I also want to disable/enable primary keys as I believe this will speed up the insertion process.
NOTE: This is over numerous tables and so I assume I need some loop to get the primary key information and run the following to drop it but I'm not sure about recreating it:
ALTER TABLE Table1
DROP CONSTRAINT PK_Table1_Col1
IIRC clustered indexes cannot be disabled as they govern where the actual data is stored in the pages.
I'm pretty sure you would have to drop the key and re-create it after your insert. Depending on the size of the tables, indexes and insert this may not save you any time.
Run This :
//For disable all constraint of your all tables
exec sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
//Your insert query here ......................
//After Insert Enable all the constraint
exec sp_MSforeachtable 'ALTER TABLE ? CHECK CONSTRAINT ALL'

TRUNCATE TABLES with CONSTRAINTS

Is there a way to truncate tables with constraints ?
I tried to DEACTIvATE with this:
DECLARE #SQLtxt varchar(max)
SET #SQLtxt = '-- DESACTIVER LES CONTRAINTES' + CHAR(10)
SELECT #SQLtxt = #SQLtxt + 'ALTER TABLE [' + name + '] NOCHECK CONSTRAINT ALL;' FROM sys.tables
PRINT #SQLtxt
Of course, it didn't worked. I have to drop the constraint then recreate them ! The only way I could make it work is by extracting the script to drop and recreate the contraint.
Is there another way ? BTW I don't want to delete because it would use the Transaction Log.
Here is a script that may help you get going scripting out FK's. Script out your foreign keys.
I use a modified version to dump the constraint definitions into a temp table, then do the TRUNCATE magic and then recreate the constraints from the temp table. However, this is only for my own convenience when restoring the production database onto a non-production environment to get rid of most of the data. Not sure, I would use it in a production scenario though. I would rather prefer deleting in small batches knowing that everything is fully logged.
Btw, womb's reference to the SQL Server 2000 Books Online is a bit misleading. TRUNCATE TABLE has always been a minimally logged operation.
TRUNCATE TABLE removes the data by deallocating the data pages used to store the table's data, and only the page deallocations are recorded in the transaction log.
This is has specified more precisely in later versions of Books Online.
The TRUNCATE command will not work on tables with FK references. Straight from the documentation:
You cannot use TRUNCATE TABLE on a
table referenced by a FOREIGN KEY
constraint; instead, use DELETE
statement without a WHERE clause.
Because TRUNCATE TABLE is not logged,
it cannot activate a trigger.
You sort of answered the question yourself - if there's a foreign key referencing your table, SQL Server needs that information in the transaction log. Since TRUNCATE TABLE effectively bypasses the log, it's not allowed on tables referenced by foreign keys.
You'll either have to DROP the foreign key constraint, or use a DELETE statement.
It's only referencing (eg the REFERENCES bit) foreign keys you need to drop.
This should make it easier...

Cleaning up a database

I have a database with hundreds of tables.
I am building a script to delete all of the rows in this database.
Of course, being a relational database, I have to delete rows from the children before I can touch the parents.
Is there something I can use for this or do I have to do this the hard way?
EDIT
Accepted Answer was modified to include Disable Trigger as well
EXEC sp_MSForEachTable 'DISABLE TRIGGER ALL ON ? '
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'ENABLE TRIGGER ALL ON ? '
You can disable all the constraints, then delete all the data, and enable the constraints again. You can put the code in a stored procedure for reutilization. Something quick and dirty:
CREATE PROCEDURE sp_EmplyAllTable
AS
EXEC sp_MSForEachTable ‘ALTER TABLE ? NOCHECK CONSTRAINT ALL’
EXEC sp_MSForEachTable ‘DELETE FROM ?’
EXEC sp_MSForEachTable ‘ALTER TABLE ? CHECK CONSTRAINT ALL’
GO
I'm guessing you want the structure without any of the data?
Can you script the tables / sp's / user-defined functions / triggers / permissions etc. and then drop the database before recreating it with the script?
This link explains how to generate a script for all the objects in a database using SQL server Management studio... http://msdn.microsoft.com/en-us/library/ms178078.aspx
If this were MySQL, I would use "mysqldump --no-data" to make a backup of the database metadata only. Then I would drop the database entirely and restore my data-less backup.
In addition to being a three-step process, it is a lot faster just in terms of transactions and I/O than deleting from each table individually. And it also shrinks the tablespace on disk, which deleting would not do (for InnoDB, that is).
I'm not familiar with Microsoft SQL Server's backup tools, is there some equivalent option?
I think I've found something promising: How to: Generate a Script (SQL Server Management Studio)
To generate a script of an entire
database
In Object Explorer, connect to an instance of the SQL Server Database
Engine and then expand that instance.
Expand Databases, right-click any database, point to Tasks, point to
Generate Scripts, and then follow the
steps in the Generate Scripts Wizard.