Table of Contents
概述:
解决方法:
应对这种情况有以下几种方法:
1、  购买第三方软件(一般估计很少人买)
2、  自己编程一个小软件来执行,但是这个逻辑性要求比较高,而且编程的能力要有一定层次,这个我暂时没有。
3、  使用本文介绍的方法,至于是啥,接着看:
使用SQLCMD在SQLServer上执行多个脚本:
第一步:先创建一个在C盘下的文件夹:C:\Scripts。然后把脚本存放到这个文件夹中:
第二步:在C盘根目录下创建一个bat文件create_db.bat,用于执行SQLCMD:
总结:
Home Database Mysql Tutorial 使用SQLCMD在SQLServer执行多个脚本

使用SQLCMD在SQLServer执行多个脚本

Jun 07, 2016 pm 03:18 PM
sqlserver use Multiple implement Script

概述: 作为 DBA ,经常要用开发人员提供的 SQL 脚本来更新正式数据库,但是一个比较合理的开发流程,当提交脚本给 DBA 执行的时候,可能已经有几百个 sql 文件,并且有执行顺序,如我现在工作的公司,十几个客户,每个客户一个库,但是数据库结构、存储过程

概述:

 

       作为DBA,经常要用开发人员提供的SQL脚本来更新正式数据库,但是一个比较合理的开发流程,当提交脚本给DBA执行的时候,可能已经有几百个sql文件,并且有执行顺序,如我现在工作的公司,十几个客户,每个客户一个库,但是数据库结构、存储过程、视图等都是一模一样,每次执行脚本(以下称为升级),如果有一百个脚本,那么就要按顺序执行过千次,这种工作量可不是一个人能承受得了的。

 

解决方法:

 

应对这种情况有以下几种方法:

 

1、  购买第三方软件(一般估计很少人买)

 

2、  自己编程一个小软件来执行,但是这个逻辑性要求比较高,而且编程的能力要有一定层次,这个我暂时没有。

 

3、  使用本文介绍的方法,至于是啥,接着看:

 

使用SQLCMD在SQLServer上执行多个脚本:

 

             SQLCMD:使用 sqlcmd 实用工具,可以在命令提示符处、在 SQLCMD 模式下的查询编辑器中、在 Windows 脚本文件中或者在 SQL Server 代理作业的操作系统 (Cmd.exe) 作业步骤中输入 Transact-SQL 语句、系统过程和脚本文件。 此实用工具使用 ODBC 执行 Transact-SQL 批处理。(来源于MSDN)详细语法可以到网上查找,这里就不贴出来。

 

       SQLCMD有一个很重要的命令::r,记住,SQLCMD是大小写敏感的。当:r发现正在运行SQL脚本,它会告诉SQLCMD把这个文件所引用的文件一并放入调用脚本中。这将告诉你,停止目前的单个查询。并重新调整查询,把应该关联的查询放到适当的位置。另外,使用:r命令在一个批处理中执行多个脚本,使得你可以定义一个单独的变量集,用于包含所有脚本,但是不包含GO终结符。2005以后引入SQLCMD,可以用于将来替代osql工具。如果你不熟悉SQLCMD,可以认为它是一个能从操作系统执行T-SQL命令和脚本的命令行工具。

 

       下面例子中,创建5个作用在TestDB数据库上有关联的sql文件。第一个脚本叫做CREATE_DB.sql,用于创建一个叫做TestDB的数据库。这个脚本包含了4个其他的脚本(使用了:r命令。),用于生成其他表、表插入、索引创建和存储过程的创建。一个.bat文件用于创建用来执行SQLCMD命令。

 

 

第一步:先创建一个在C盘下的文件夹:C:\Scripts。然后把脚本存放到这个文件夹中:

脚本1:CREATE_DB.sql

/* SCRIPT: CREATE_DB.sql */
/* 创建TestDB数据库 */

-- This is the main caller for each script
SET NOCOUNT ON
GO

PRINT '开始创建TestDB数据库'
IF EXISTS (SELECT 1 FROM SYS.DATABASES WHERE NAME = 'TestDB')
DROP DATABASE TestDB
GO
CREATE DATABASE TestDB
GO

:On Error exit

:r c:\Scripts\CREATE_TABLES.sql
:r c:\Scripts\TABLE_INSERTS.sql
:r c:\Scripts\CREATE_INDEXES.sql
:r c:\Scripts\CREATE_PROCEDURES.sql

PRINT '创建完毕'
GO
Copy after login

 

脚本2:CREATE_INDEXES.sql

/* 创建索引 */
PRINT '开始创建索引'
GO
USE TestDB
GO
IF NOT EXISTS ( SELECT  1
                FROM    SYS.INDEXES
                WHERE   NAME = 'IX_EMPLOYEE_LASTNAME' ) 
    CREATE INDEX IX_EMPLOYEE_LASTNAME ON DBO.EMPLOYEE(LASTNAME, FIRSTNAME)
GO
IF NOT EXISTS ( SELECT  1
                FROM    SYS.INDEXES
                WHERE   NAME = 'IX_TIMECARD_EMPLOYEEID' ) 
    CREATE INDEX IX_TIMECARD_EMPLOYEEID ON DBO.TIMECARD(EMPLOYEEID)
GO
Copy after login


脚本3:CREATE_PROCEDURES.sql

/* 创建存储过程 */
PRINT '正在创建存储过程'
GO
USE TestDB
GO
IF OBJECT_ID('GET_EMPLOYEE_TIMECARDS') IS NOT NULL 
    DROP PROCEDURE DBO.GET_EMPLOYEE_TIMECARDS
GO
CREATE PROCEDURE DBO.GET_EMPLOYEE_TIMECARDS @EMPLOYEEID INT
AS 
    SET NOCOUNT ON

    SELECT  *
    FROM    DBO.EMPLOYEE E
            JOIN DBO.TIMECARD T ON E.EMPLOYEEID = T.EMPLOYEEID
    WHERE   E.EMPLOYEEID = @EMPLOYEEID
    ORDER BY DATEWORKED

GO
Copy after login


脚本4:CREATE_TABLES.sql

/* 创建数据表 */
PRINT '正在创建数据表 '
GO
USE TestDB
GO
IF OBJECT_ID('EMPLOYEE') IS NOT NULL 
    DROP TABLE DBO.EMPLOYEE
GO
CREATE TABLE DBO.EMPLOYEE
    (
      EMPLOYEEID INT IDENTITY(1, 1)
                     NOT NULL
                     PRIMARY KEY ,
      FIRSTNAME VARCHAR(50) ,
      LASTNAME VARCHAR(50)
    )
GO

IF OBJECT_ID('TIMECARD') IS NOT NULL 
    DROP TABLE DBO.TIMECARD
GO
CREATE TABLE DBO.TIMECARD
    (
      TIMECARDID INT IDENTITY(1, 1)
                     NOT NULL
                     PRIMARY KEY ,
      EMPLOYEEID INT NOT NULL ,
      HOURSWORKED TINYINT NOT NULL ,
      HOURLYRATE MONEY NOT NULL ,
      DATEWORKED DATETIME NOT NULL
    )
GO

DECLARE @TOTAL_TABLES INT
SET @TOTAL_TABLES = 2
Copy after login


脚本5:TABLE_INSERTS.sql

/* 插入表数据 */

PRINT 'TOTAL TABLES CREATED = ' + CAST(@TOTAL_TABLES AS VARCHAR)
GO
PRINT '正在插入数据到表 EMPLOYEE'
GO
USE TestDB
GO
INSERT  INTO DBO.EMPLOYEE
        ( FIRSTNAME, LASTNAME )
        SELECT  'JOHN' ,
                'DOE'
GO
INSERT  INTO DBO.EMPLOYEE
        ( FIRSTNAME, LASTNAME )
        SELECT  'JANE' ,
                'DOE'
GO
INSERT  INTO DBO.EMPLOYEE
        ( FIRSTNAME, LASTNAME )
        SELECT  'JEFF' ,
                'DOE'
GO
Copy after login


 

第二步:在C盘根目录下创建一个bat文件create_db.bat,用于执行SQLCMD:

 

SQLCMD -E -dmaster -ic:\Scripts\create_db.sql
PAUSE
Copy after login

 


第三步:在C盘下直接执行bat文件:

 

双击文件可以看到:

在执行前,是没有TestDB:

使用SQLCMD在SQLServer执行多个脚本

 

执行中:

使用SQLCMD在SQLServer执行多个脚本

 

执行后,该创建的东西都创建出来了:

 

使用SQLCMD在SQLServer执行多个脚本

 

由于执行的顺序已经在脚本1中定义好,所以直接执行即可,并且执行成功。

 

总结:

             根据个人经验,还是开发一个批量执行工具会比较好,这个方法在少量脚本的时候可以选用。

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
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 solve the problem that the object named already exists in the sqlserver database How to solve the problem that the object named already exists in the sqlserver database Apr 05, 2024 pm 09:42 PM

For objects with the same name that already exist in the SQL Server database, the following steps need to be taken: Confirm the object type (table, view, stored procedure). IF NOT EXISTS can be used to skip creation if the object is empty. If the object has data, use a different name or modify the structure. Use DROP to delete existing objects (use caution, backup recommended). Check for schema changes to make sure there are no references to deleted or renamed objects.

How to check sqlserver port number How to check sqlserver port number Apr 05, 2024 pm 09:57 PM

To view the SQL Server port number: Open SSMS and connect to the server. Find the server name in Object Explorer, right-click it and select Properties. In the Connection tab, view the TCP Port field.

How to recover accidentally deleted database in sqlserver How to recover accidentally deleted database in sqlserver Apr 05, 2024 pm 10:39 PM

If you accidentally delete a SQL Server database, you can take the following steps to recover: stop database activity; back up log files; check database logs; recovery options: restore from backup; restore from transaction log; use DBCC CHECKDB; use third-party tools. Please back up your database regularly and enable transaction logging to prevent data loss.

Where is the sqlserver database? Where is the sqlserver database? Apr 05, 2024 pm 08:21 PM

SQL Server database files are usually stored in the following default location: Windows: C:\Program Files\Microsoft SQL Server\MSSQL\DATALinux: /var/opt/mssql/data The database file location can be customized by modifying the database file path setting.

What to do if the sqlserver service cannot be started What to do if the sqlserver service cannot be started Apr 05, 2024 pm 10:00 PM

When the SQL Server service fails to start, here are some steps to resolve: Check the error log to determine the root cause. Make sure the service account has permission to start the service. Check whether dependency services are running. Disable antivirus software. Repair SQL Server installation. If the repair does not work, reinstall SQL Server.

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

See all articles