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

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 ?'

Related

How to update table definitions for many tables?

We want to update our out-of-sync tables in our database to match a different sql server database instance. We want to preserve the data in the database tables but will need to update contraints and column definitions. What is the easiest technique for accomplishing this?
Brute force, but fairly easy to script would be to:
On the current data base (schemas you want), right-click on the DB and select Tasks > Generate Scripts...
Change the relevant parameters for what you need and save the script file (make sure you select the options to script all the indexes, triggers, etc.).
Create a fresh staging DB and run the script there.
Export all the data from the out-of-sync DB to the staging DB.
Drop all the tables on the out-of-sync DB.
Run the script on the out-of-sync DB.
Import all the data into the out-of-sync DB from the staging DB.
Delete the staging DB.
Obviously, you'll need to verify your data at the various steps before you go dropping tables or databases.

How to recover table after drop it in SQL Server

I drop a table in SQL Server using this code:
DROP TABLE temp
Now, I try to recover this table, but I don't know a solution.
Please, tell me a solution for this problem if you know.
If DROP TABLE was executed inside the Transaction and it has not been committed then you can ROLLBACK. But if it isn't, then you need backup of your database. Recover your table from database. If backup is also not present, then search for 3rd party recovery tools.

Can I change a SQL Server table name in a way that is backwards compatible? E.g add a permanent alias?

I have a Sql Server 2008 database I inherited. A number of apps and SSIS packages work off that database. Not too long ago the scope of the database changed and a lot of new tables were added. As a result of this a lot of the table names (and even the database name itself) no longer make sense, resulting in a very confusing schema.
I could rename the tables straight away and change the apps and processes to use the new names but the chaos and downtime it would cause in the meantime would not be acceptable.
Is there a way I can add an alternate name for a table (like a permanent alias) that I could use to refer to either the new or old table name until all of my refactoring is complete?
Create a synonym first.
CREATE SYNONYM dbo.SensibleName FOR dbo.CrazyName;
Now find all the references to CrazyName in your codebase, and update them to reference SensibleName instead. Once you believe you have found them all, you can eventually run:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
DROP SYNONYM dbo.SensibleName;
EXEC sp_rename N'dbo.CrazyName', N'SensibleName', N'OBJECT';
COMMIT TRANSACTION;
If you need to make column names more sensible, you'll have to do so using a view, as synonyms only cover a subset of database-level objects.
Some other info here.
You can rename it with sp_rename and then add synonym:
CREATE SYNONYM OldTableName FOR NewTableName

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/

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.