Recreate Database Schema-Only - sql-server

I want to make a process for recreating a database schema-only. Not a backup/restore but standing up a schema-only copy of a database on a different server, that we would populate with data manually. I was thinking about using SMO in powershell. Does anyone know what the best approach for this would be? Prefer to stay away from 3rd party options, I have the time to do it myself.
Thanks!

One way is to use DBCC CLONEDATABASE(structures + statistics):
DBCC CLONEDATABASE('original_db_name', 'cloned_db')
ALTER DATABASE [cloned_db] SET READ_WRITE WITH NO_WAIT
Backup
Restore on second server
ALTER DATABASE [cloned_db] MODIFY NAME = original_db_name;

Related

Best way to make all tables read only

I have a SQL Server 2016 database of which I am the owner. It's an archive that's no longer accessible to anyone else. I still need to read this database by linking to it from other SQL Server databases and from Access.
I would like to be able to alter and create views in this database but I would like to prevent myself from inadvertently changing any data there.
What's the quickest, easiest, and easily reversible way to allow myself only select access to all the tables?
alter database current set read_only
To reverse, or if you want to modify views, run
alter database current set read_write
No permissions-based solution is effective against the database owner.

Is there a command to stop using a database in SQL Server?

I'm refering to when we say USE dbTest we start using that database and we can create tables and what not, and if we want to change databases we could just say USE dbNotatest and it would change the database we're using.
But is there a way to stop using the database we selected in the first place, without starting to use another one?
To stop using a database, you will need to change your database context. For example, if you are trying to drop your database and you are in the context of that database, simply switch to another database (commonly master or tempdb).
If other connections are open to the database and preventing you from dropping the database, you will need to kill the connected spids. This can be tedious, so an option to force close all connections and then drop your database that usually works for me is:
use [master];
ALTER DATABASE [foo] SET OFFLINE WITH ROLLBACK IMMEDIATE;
ALTER DATABASE [foo] SET ONLINE;
DROP DATABASE [foo];
By taking the database offline with rollback immediate, I force all connections closed and rollback any open transactions. Now, I could drop it while it is offline, but if I do the database files will remain on the file system. Dropping a database online will remove the database files, so I bring it back online before I drop it.
There is no option in SQL Server.
you can use only use query to manipulate other databasees otherwise you don have any options.
you can detach it just by using another database . for example in Microsoft sql sever management you can use the test database that already exists

Best way to auto-restore a database every hour

I have a demo site where anyone can login and test a management interface.
Every hour I would like to flush all the data in the SQL 2008 Database and restore it from the original.
Red Gate Software has some awesome tools for this, however they are beyond my budget right now.
Could I simply make a backup copy of the database's data file, then have a c# console app that deletes it and copies over the original. Then I can have a windows schedule task to run the .exe every hour.
It's simple and free... would this work?
I'm using SQL Server 2008 R2 Web edition
I understand that Red Gate Software is technically better because I can set it to analyze the db and only update the records that were altered, and the approach I have above is like a "sledge hammer".
It's simple and free... would this work?
Yes, you could do it like that, just remember to put the DB in single user mode before restoring it otherwise your restore will fail
example script
USE master
GO
ALTER DATABASE YourDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
RESTORE DATABASE YourDB FROM DISK=N'D:\Backup\Pristine.BAK' WITH FILE = 1,
NOUNLOAD, REPLACE, STATS = 10
GO
ALTER DATABASE YourDB SET MULTI_USER
GO
This can be scripted using SQL and scheduled as a job on the server to execute once an hour. Since you have a backup copy, I assume, that is pristine, then all you need to do is take the database offline, restore from the backup, bring the database back online. All of this can be scripted. Do you need the scripts?
You could also detach the database, overwrite the data and log files from your template (previously detached) and then re-attach.

Best way to copy a database (SQL Server 2008)

Dumb question - what's the best way to copy instances in an environment where I want to refresh a development server with instances from a production server?
I've done backup-restore, but I've heard detach-copy-attach and one guy even told me he would just copy the datafiles between the filesystems....
Are these the three (or two, the last one sounds kind of suspect) accepted methods?
My understanding is that the second method is faster but requires downtime on the source because of the detach aspect.
Also, in this situation (wanting an exact copy of production on a dev server) what's the accepted practice for transferring logins,etc.? Should I just backup and restore the user databases + master + msdb?
Easiest way is actually a script.
Run this on production:
USE MASTER;
BACKUP DATABASE [MyDatabase]
TO DISK = 'C:\temp\MyDatabase1.bak' -- some writeable folder.
WITH COPY_ONLY
This one command makes a complete backup copy of the database onto a single file, without interfering with production availability or backup schedule, etc.
To restore, just run this on your dev or test SQL Server:
USE MASTER;
RESTORE DATABASE [MyDatabase]
FROM DISK = 'C:\temp\MyDatabase1.bak'
WITH
MOVE 'MyDatabase' TO 'C:\Sql\MyDatabase.mdf', -- or wherever these live on target
MOVE 'MyDatabase_log' TO 'C:\Sql\MyDatabase_log.ldf',
REPLACE, RECOVERY
Then save these scripts on each server. One-click convenience.
Edit:
if you get an error when restoring that the logical names don't match, you can get them like this:
RESTORE FILELISTONLY
FROM disk = 'C:\temp\MyDatabaseName1.bak'
If you use SQL Server logins (not windows authentication) you can run this after restoring each time (on the dev/test machine):
use MyDatabaseName;
sp_change_users_login 'Auto_Fix', 'userloginname', null, 'userpassword';
The fastest way to copy a database is to detach-copy-attach method, but the production users will not have database access while the prod db is detached. You can do something like this if your production DB is for example a Point of Sale system that nobody uses during the night.
If you cannot detach the production db you should use backup and restore.
You will have to create the logins if they are not in the new instance. I do not recommend you to copy the system databases.
You can use the SQL Server Management Studio to create the scripts that create the logins you need. Right click on the login you need to create and select Script Login As / Create.
This will lists the orphaned users:
EXEC sp_change_users_login 'Report'
If you already have a login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user'
If you want to create a new login id and password for this user, fix it by doing:
EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'
UPDATE:
My advice below tells you how to script a DB using SQL Server Management Studio, but the default settings in SSMS miss out all sorts of crucial parts of a database (like indexes and triggers!) for some reason. So, I created my own program to properly script a database including just about every type of DB object you may have added. I recommend using this instead. It's called SQL Server Scripter and it can be found here:
https://bitbucket.org/jez9999/sqlserverscripter
I'm surprised no-one has mentioned this, because it's really useful: you can dump out a database (its schema and data) to a script, using SQL Server Management Studio.
Right-click the database, choose "Tasks | Generate Scripts...", and then select to script specific database objects. Select the ones you want to copy over to the new DB (you probably want to select at least the Tables and Schemas). Then, for the "Set Scripting Options" screen, click "Advanced", scroll down to "Types of data to script" and select "Schema and data". Click OK, and finish generating the script. You'll see that this has now generated a long script for you that creates the database's tables and inserts the data into them! You can then create a new database, and change the USE [DbName] statement at the top of the script to reflect the name of the new database you want to copy the old one to. Run the script and the old database's schema and data will be copied to the new one!
This allows you to do the whole thing from within SQL Server Management studio, and there's no need to touch the file system.
Below is what I do to copy a database from production env to my local env:
Create an empty database in your local sql server
Right click on the new database -> tasks -> import data
In the SQL Server Import and Export Wizard, select product env's servername as data source. And select your new database as the destination data.
Its hard to detach your production dB or other running dB's and deal with that downtime, so I almost always use a Backup / restore method.
If you also want to make sure to keep your login's in sync check out the MS KB article on using the stored proc sp_help_revlogin to do this.
The detach/copy/attach method will take down the database. That's not something you'd want in production.
The backup/restore will only work if you have write permissions to the production server. I work with Amazon RDS and I don't.
The import/export method doesn't really work because of foreign keys - unless you do tables one by one in the order they reference one another. You can do an import/export to a new database. That will copy all the tables and data, but not the foreign keys.
This sounds like a common operation one needs to do with database. Why isn't SQL Server handling this properly? Every time I had to do this it was frustrating.
That being said, the only painless solution I've encountered was Sql Azure Migration Tool which is maintained by the community. It works with SQL Server too.
I run an SP to DROP the table(s) and then use a DTS package to import the most recent production table(s) onto my development box.
Then I go home and come back the following morning. It's not elegant; but it works for me.
If you want to take a copy of a live database, do the Backup/Restore method.
[In SQLS2000, not sure about 2008:] Just keep in mind that if you are using SQL Server accounts in this database, as opposed to Windows accounts, if the master DB is different or out of sync on the development server, the user accounts will not translate when you do the restore. I've heard about an SP to remap them, but I can't remember which one it was.

How best to copy entire databases in MS SQL Server?

I need to copy about 40 databases from one server to another. The new databases should have new names, but all the same tables, data and indexes as the original databases. So far I've been:
1) creating each destination database
2) using the "Tasks->Export Data" command to create and populate tables for each database individually
3) rebuilding all of the indexes for each database with a SQL script
Only three steps per database, but I'll bet there's an easier way. Do any MS SQL Server experts out there have any advice?
Given that you're performing this on multiple databases -- you want a simple scripted solution, not a point and click solution.
This is a backup script that i keep around.
Get it working for one file and then modify it for many.
(on source server...)
BACKUP DATABASE Northwind
TO DISK = 'c:\Northwind.bak'
(target server...)
RESTORE FILELISTONLY
FROM DISK = 'c:\Northwind.bak'
(look at the device names... and determine where you want the mdf and
ldf files to go on this target server)
RESTORE DATABASE TestDB
FROM DISK = 'c:\Northwind.bak'
WITH MOVE 'Northwind' TO 'c:\test\testdb.mdf',
MOVE 'Northwind_log' TO 'c:\test\testdb.ldf'
GO
Maybe the easiest is to detach/reattach. Right-click in the server manager on the DB, tasks --> detach. Then copy the MDF/LDF files to the new server and then reattach by clicking on the server icon and tasks-->attach. It will ask you for the MDF file - make sure the name etc is accurate.
In order of ease
stop server/fcopy/attach is probably easiest.
backup/restore - can be done disconnected pretty simple and easy
transfer DTS task - needs file copy permissions
replication - furthest from simple to setup
Things to think about permissions, users and groups at the destination server esp. if you're transferring or restoring.
There are better answers already but this is an 'also ran' because it is just another option.
For the low low price of free you could look at the Microsoft SQL Server Database Publishing Wizard. This tool allows you to script the schema, data or data and schema. Plus is can be run from a UI or command line <- think CI process.
Backup -> Restore is the simplest, if not to use the replication.
If you use the Backup/Restore solution you're likely to have orphaned users so be sure to check out this article<microsoft> on how to fix them.
Another one to check out that is quick and simple:
Simple SQL BULK Copy
http://projects.c3o.com/files/3/plugins/entry11.aspx
Backup the databases using the standard SQL backup tool in Enterprise Manager, then when you restore on the second server you can specify the name of the new database.
This is the best way to maintain the schema in its entirety.
use backups to restore the databases to the new server with the new names.
Redgate SQL Compare and SQL Data Compare. The Comparison Bundle was by far the best investment a company I worked for ever made. Moving e-training content was a breeze with it.
Check those links:
For multiple db's backup
and single db restore

Resources