I want to create an SQL script that creates a database. Right now, I have this:
CREATE DATABASE [Documents] ON PRIMARY
( NAME = N'Documents', FILENAME = N'Documents.mdf')
LOG ON
( NAME = N'Documents_log', FILENAME = N'Documents_log.ldf')
COLLATE SQL_Latin1_General_CP1_CI_AS
However, this generates the following error:
Msg 5105, Level 16, State 2, Line 2
A file activation error occurred. The physical file name 'Documents.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation.
Msg 1802, Level 16, State 1, Line 2
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
I know the problem is that I did not specify fully qualified path for the filenames. But I want to be able to run this script regardless of the directory structure of the database server. Is there some way to use a default path?
7条答案
按热度按时间cnwbcb6i1#
Create the database 'Documents' and give file properties through an alter.
This script is more portable and can be deployed in multiple servers without any modifications.
uyhoqukh2#
You can create a database without specifying file details, like:
lxkprmvk3#
See How do I find the data directory for a SQL Server instance?
If you are using SQL Server 2012 or higher, you can find the default path using
You can then use exec() to construct your CREATE DATABASE statement.
This is useful if you want the physical file names of your database to be different from the default name.
vnjpjtjt4#
Adding onto @Blade's answer. Here's an example of getting the default path server properties and using the EXECUTE method:
Note that if you do a
USE
to switch dbs, the local variable scope is lost. So if you're creating multiple dbs in a script, either create them all at the beginning or copy the variables' declare/set to each create.xjreopfe5#
I believe that you can do
without the ON .... and it will get created with defaults for path and the rest.
aoyhnmkz6#
Take a Look on how to create a Default Path . See if it helps on what you are looking for.
Cheers,
rks48beu7#
Taking in account all the answers and some information from the Internet I played with the next code:
I use it as the 'tool' for some testing needs. I left 2 different approaches to use EXEC per command (after IF operator) and to execute several commands at once. Hope it will help somebody.