创建数据库并将mdf文件移动到SQL默认位置

时间:2014-03-06 05:48:01

标签: sql-server database ssms

我想用临时位置中的.mdf文件在SQL中创建一个数据库说C:\Temp

我使用以下查询

USE [master]
GO
CREATE DATABASE [database_name] ON 
( FILENAME = N'C:\temp\temp.mdf' ),
( FILENAME = N'C:\temp\temp.ldf' )
FOR ATTACH ;
GO

但我希望在附加时将mdf和ldf文件复制到SQL默认路径(C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Data\),因为临时位置可能会在将来被删除或更改。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

在附加之前,您需要将文件复制/移动到所需的目录中。 如果您希望从SQL中完全完成,则需要:

  • 启用xp_cmdshell
  • 执行如下脚本:

    USE [master]
    GO
    DECLARE @result int
    EXEC @result = xp_cmdshell 'copy c:\temp\temp.mdf
        C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Data\temp.mdf';
    IF (@result = 0)
        EXEC @result = xp_cmdshell 'copy c:\temp\temp.ldf
            C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Data\temp.ldf';
        IF (@result = 0)
            CREATE DATABASE [database_name] ON 
            (FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Data\temp.mdf'),
            (FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Data\temp.ldf')
            FOR ATTACH ;
            GO
        ELSE
            PRINT 'Failure'
    ELSE
        PRINT 'Failure'
    

答案 1 :(得分:0)

为避免由于目录路径中的空格而导致错误,请使用双引号。

USE [master]
GO
DECLARE @result int
EXEC @result = xp_cmdshell 'copy "c:\temp\temp.mdf" "C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Data\temp.mdf"';

IF (@result = 0)
Begin
    EXEC @result = xp_cmdshell 'copy "c:\temp\temp.ldf" "C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Data\temp.ldf"';
    IF (@result = 0)
    Begin
        CREATE DATABASE [Your_Database_Name] ON 
        (FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Data\temp.mdf'),
        (FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Data\temp.ldf')
        FOR ATTACH ;
    End
    ELSE
        PRINT 'Failure'
End
ELSE
    PRINT 'Failure'