Cleaning up a database - sql

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.

Related

SQL alter schema multiple tables at once

I recently upsized my MS-Access database to SQL Server and in the process successfully exported a bunch of tables.
However, now the imported tables are prefixed with MSH-CHAMBERS\mfanimpela which I assume is my username and this is the schema (or owner property).
While I have seen posts on changing EACH table schema to the desired 'dbo', I want a statement that can help me change ALL of my tables (since these are so many).
Please help - chagbert.
Use the sp_MSForEachTable procedure like this:
EXEC **sp_MSForEachTable** 'ALTER SCHEMA dbo TRANSFER ?'
-- in the above example dbo is the targeted schema where you want to place your tables
Google sp_MSForEachTable and use it to call sp_rename
You might need to do additional checks before you rename the table to avoid mistakes.

Given a SQL Express database base file (.MDF) how can I wipe/clear/reset the schema and/or data?

Whats options do I have to clear the schema and data from a MDF file? What options to delete all the data?
To reset a databases schema, it seems I need to copy a file from a backup of the database when it was empty. I was wondering if there was a simpler or more efficient way.
To clear all data, it seems I'd need to write a script. The script would disable constraints, then drop all rows from each table before turning back on constraints. This is straightforward but does require I discover/track what tables exist in the database. Maybe its not sufficient or there is an easier approach?
I'm not sure what the point is of 'clearing the schema' - surely a new database already has a 'clear' schema.. BUT, you can create a new database in code via the following T-SQL:
USE Master
CREATE DATABASE NewDb (NAME=NewDbFile, FILENAME= '<filepath>')
If you need a file (an MDF) you can then detach the database too with sp_detach_db and you can then move it as required from the location specified above:
EXEC sp_detach_db NewDb
To clear the data you can use sp_msforeachtable with a truncation command - it is a non-logged operation, and does not check constraints, nor foreign keys - however, it cannot be rolled back!
EXEC sp_msforeachtable 'TRUNCATE TABLE ?'

sql server: delete all the rows of all the tables

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.

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/

adding lock option to Create Table statement in Sql Server 2005

I am busy creating tables in Sql Server from a Sybase database. In the Sybase database when the tables are created an option 'lock allpages' was used, how can I replicate this when creating the tables in Sql Server 2005.
In SQL Server you cannot specify a lock option for the table in CREATE TABLE. You can at most disable row level and page level locking by adding the WITH ALLOW_ROW_LOCKS = OFF or WITH ALLOW_PAGE_LOCKS_OFF. The equivalent of locking the entire table in SQL Server is to use a lock hint WITH (TABLOCK) when running queries and updates on the table, but that is not recommended.
My recommendation would be to just ignore this option when transferring the tables from Sybase to SQL Server.
What do you want to achieve with this "lock allpages" option? Is the database you're working on up and running productively? If not, in SQL Server, you can restrict access to the entire database to a single user:
ALTER DATABASE YourDatabaseName SET SINGLE_USER
and that way you're sure no one else if going to come in your way and fiddle around until you're totally done :-)
Set it back to "normal" usage with:
ALTER DATABASE YourDatabaseName SET MULTI_USER
Marc