CREATE DATABASE using file in default path

前端 未结 6 1615
借酒劲吻你
借酒劲吻你 2021-02-05 03:28

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


        
6条回答
  •  忘掉有多难
    2021-02-05 04:31

    Adding onto @Blade's answer. Here's an example of getting the default path server properties and using the EXECUTE method:

    DECLARE @DefaultDataPath varchar(max)
    SET @DefaultDataPath = (SELECT CONVERT(varchar(max), SERVERPROPERTY('INSTANCEDEFAULTDATAPATH')))
    DECLARE @DefaultLogPath varchar(max)
    SET @DefaultLogPath = (SELECT CONVERT(varchar(max), SERVERPROPERTY('INSTANCEDEFAULTLOGPATH')))
    
    EXECUTE('
    CREATE DATABASE [blah] ON PRIMARY
    ( NAME = N''blah'', FILENAME = ''' + @DefaultDataPath + 'blah.mdf'', SIZE = 167872KB, MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB )
     LOG ON
    ( NAME = N''blah_Log'', FILENAME = ''' + @DefaultDataPath + 'blah_Log.mdf'', SIZE = 2048KB, MAXSIZE = 2048GB, FILEGROWTH = 16384KB );
    COLLATE SQL_Latin1_General_CP1_CI_AS;
    ');
    GO
    

    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.

提交回复
热议问题