Home Database Mysql Tutorial How to batch attach databases to MS SQLServer

How to batch attach databases to MS SQLServer

Oct 18, 2017 am 10:07 AM
sqlserver database method


/************************************************************  
 * 标题:MS SQLServer 批量附加数据库  
 * 说明:请根据下面的注释使用此脚本  
 * 时间: 2015/7/13 11:16:41  
 ************************************************************/  
  USE MASTER  
GO  
  IF OBJECT_ID('[sp_AttchDataBase]') IS NOT NULL  
    DROP PROCEDURE [sp_AttchDataBase]  GO  
  /*附加数据库(V2.0) Andy 2011-7-8 */  CREATE PROCEDURE sp_AttchDataBase(  
    @Path       NVARCHAR(1024),  
    @DataFiles  NVARCHAR(MAX) = NULL,  
    @SplitStr   NVARCHAR(50) = ','  )  
AS  
    SET NOCOUNT ON  
      
    /*  
    V2.0 版本,在V1.0基础上,处理文件路径不规范原則,e.g. @DataFiles='E:\"my data DB"\"Hello RT"'  
      
    @Path       文件路径  
    @DataFiles  文件名列表  
    @SplitStr   文件名列表中的文件分隔符  
      
    1.必须把要附加的数据库文件(*.mdf和*.ldf)放到@Path下,  
    2.当@DataFiles Is Null 会附加@Path文件夹下的所有数据库文件.  
      
    e.g:  
    Exec sp_AttchDataBase 'D:\db2'  
    */  
      
      
    --检查文件路径是否正确  
    DECLARE @Dir  NVARCHAR(1024),  
            @i    INT,  
            @x    XML  
      
    IF RIGHT(@Path, 1) <> &#39;\&#39;  
        SET @Path = @Path + &#39;\&#39;  
      
    IF CHARINDEX(&#39;\\&#39;, @Path) > 0  
    BEGIN  
        --RAISERROR 50001 N&#39;文件路径中不能包含有"\\",@Path设置错误.&#39;  
        RETURN(1)  
    END  
      
    SET @Dir = &#39;Dir &#39; + @Path  
    EXEC @i = xp_cmdshell @Dir,  
         no_output  
      
    IF @i <> 0  
    BEGIN  
        --RAISERROR 50001 N&#39;无效的文件路径,@Path设置错误.&#39;  
        RETURN(1)  
    END  
      
    SET @Path = REPLACE(@Path, &#39;"&#39;, &#39;&#39;) /*处理文件路径不规范原則*/  
      
    DECLARE @Files               TABLE(NAME NVARCHAR(512))  
    DECLARE @filetmpfin          TABLE(  
                NAME NVARCHAR(255) NOT NULL,  
                depth INT NULL,  
                IsFile BIT NULL  
            )  
      
    DECLARE @SmoPrimayChildren   TABLE(  
                STATUS INT,  
                fileid INT,  
                NAME SYSNAME,  
                FILENAME NVARCHAR(512)  
            )  
      
    DECLARE @smoPrimaryFileProp  TABLE(PROPERTY SQL_VARIANT NULL, VALUE SQL_VARIANT NULL)  
      
    SET @DataFiles = REPLACE(  
            REPLACE(REPLACE(@DataFiles, CHAR(13) + CHAR(10), &#39;&#39;), CHAR(13), &#39;&#39;),  
            CHAR(10),  
            &#39;&#39;  
        )  
      
    SET @x = N&#39;<Root><File>&#39; + REPLACE(@DataFiles, @SplitStr, N&#39;</File><File>&#39;) +   
        N&#39;</File></Root>&#39;  
      
      
    INSERT INTO @Files  
    SELECT t.v.value(&#39;.[1]&#39;, &#39;nvarchar(512)&#39;) AS NAME  
    FROM   @x.nodes(&#39;Root/File&#39;) t(v)  
    WHERE  t.v.value(&#39;.[1]&#39;, &#39;nvarchar(512)&#39;) > &#39;&#39;  
      
      
    INSERT INTO @filetmpfin  
    EXEC MASTER.dbo.xp_dirtree @Path,  
         1,  
         1  
      
    DECLARE @File      NVARCHAR(255),  
            @sql       NVARCHAR(4000),  
            @DataBase  SYSNAME  
      
      
      
    DECLARE cur_File   CURSOR    
    FOR  
        SELECT NAME  
        FROM   @filetmpfin AS a  
        WHERE  IsFile = 1  
               AND NAME LIKE &#39;%.mdf&#39;  
               AND (  
                       EXISTS(  
                           SELECT 1  
                           FROM   @Files  
                           WHERE  NAME = a.Name  
                       )  
                       OR @DataFiles IS NULL  
                   )  
               AND NOT EXISTS(  
                       SELECT 1  
                       FROM   MASTER.sys.master_files  
                       WHERE  physical_name = @Path + a.Name  
                   )  
      
    OPEN cur_File  
      
    BEGIN TRY  
        FETCH NEXT FROM cur_File INTO @File  
        WHILE @@Fetch_Status = 0  
        BEGIN  
            SET @sql = &#39;dbcc checkprimaryfile (N&#39;&#39;&#39; + @Path + @File + &#39;&#39;&#39; , 2) With No_Infomsgs&#39;  
              
            INSERT INTO @smoPrimaryFileProp  
            EXEC (@sql)  
              
            SET @sql = &#39;dbcc checkprimaryfile (N&#39;&#39;&#39; + @Path + @File + &#39;&#39;&#39; , 3) With No_Infomsgs&#39;  
              
            INSERT INTO @SmoPrimayChildren  
            EXEC (@sql)  
              
            SELECT @DataBase = QUOTENAME(CONVERT(NVARCHAR(255), VALUE)),  
                   @sql = NULL  
            FROM   @smoPrimaryFileProp  
            WHERE  CONVERT(NVARCHAR(255), PROPERTY) = &#39;Database name&#39;  
              
            SELECT @sql = ISNULL(  
                       @sql + &#39;,&#39; + CHAR(13) + CHAR(10),  
                       &#39;Create DataBase &#39; + @DataBase + &#39; On&#39; + CHAR(13) + CHAR(10)  
                   ) +  
                   &#39;(FileName=N&#39;&#39;&#39; + @Path + RIGHT(  
                       RTRIM(FILENAME),  
                       CHARINDEX(&#39;\&#39;, REVERSE(RTRIM(FILENAME))) -1  
                   ) + &#39;&#39;&#39;)&#39;  
            FROM   @SmoPrimayChildren  
              
            EXEC (@sql + &#39; For Attach&#39;)  
              
            PRINT N&#39;成功附加数据库: &#39; + @DataBase  
              
            DELETE   
            FROM   @SmoPrimayChildren  
              
            DELETE   
            FROM   @smoPrimaryFileProp  
              
            FETCH NEXT FROM cur_File INTO @File  
        END  
    END TRY  
    BEGIN CATCH  
        DECLARE @Error NVARCHAR(2047)  
        SET @Error = ERROR_MESSAGE()  
        --RAISERROR 50001 @Error  
    END CATCH  
      
      
    CLOSE cur_File  
    DEALLOCATE cur_File  
GO  
  /************************************************************  
 * 调用方式  
 ************************************************************/  --use master  --Go  
   --Exec sp_AttchDataBase   --        @Path = &#39;E:\100.其他\测试&#39;, -- nvarchar(1024)  --        @DataFiles = NULL, -- nvarchar(max)  --        @SplitStr = NULL -- nvarchar(50)
Copy after login

 

The above is the detailed content of How to batch attach databases to MS SQLServer. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to import mdf file into sqlserver How to import mdf file into sqlserver Apr 08, 2024 am 11:41 AM

The import steps are as follows: Copy the MDF file to SQL Server's data directory (usually C:\Program Files\Microsoft SQL Server\MSSQL\DATA). In SQL Server Management Studio (SSMS), open the database and select Attach. Click the Add button and select the MDF file. Confirm the database name and click the OK button.

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

What is the difference between mysql and sqlserver syntax What is the difference between mysql and sqlserver syntax Apr 22, 2024 pm 06:33 PM

The syntax differences between MySQL and SQL Server are mainly reflected in database objects, data types, SQL statements and other aspects. Database object differences include the storage engine and how filegroups are specified, and the creation of indexes and constraints. Data type differences involve differences in numeric types, character types, and date and time types. SQL statement differences are reflected in result set limitations, data insertion, update and delete operations, etc. Other differences include how identity columns, views, and stored procedures are created. Understanding these differences is important to avoid errors when using different database systems.

How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) How to choose a mobile phone screen protector to protect your mobile phone screen (several key points and tips for purchasing mobile phone screen protectors) May 07, 2024 pm 05:55 PM

Mobile phone film has become one of the indispensable accessories with the popularity of smartphones. To extend its service life, choose a suitable mobile phone film to protect the mobile phone screen. To help readers choose the most suitable mobile phone film for themselves, this article will introduce several key points and techniques for purchasing mobile phone film. Understand the materials and types of mobile phone films: PET film, TPU, etc. Mobile phone films are made of a variety of materials, including tempered glass. PET film is relatively soft, tempered glass film has good scratch resistance, and TPU has good shock-proof performance. It can be decided based on personal preference and needs when choosing. Consider the degree of screen protection. Different types of mobile phone films have different degrees of screen protection. PET film mainly plays an anti-scratch role, while tempered glass film has better drop resistance. You can choose to have better

Where is the navicat database file? Where is the navicat database file? Apr 23, 2024 am 10:57 AM

The location where the Navicat database configuration files are stored varies by operating system: Windows: The user-specific path is %APPDATA%\PremiumSoft\Navicat\macOS: The user-specific path is ~/Library/Application Support/Navicat\Linux: The user-specific path is ~/ .config/navicat\The configuration file name contains the connection type, such as navicat_mysql.ini. These configuration files store database connection information, query history, and SSH settings.

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

See all articles