使用SQLCMD在SQLServer执行多个脚本
时间:2021-07-01 10:21:17
帮助过:72人阅读
print?
- /* SCRIPT: CREATE_DB.sql */
- /* 创建TestDB数据库 */
-
- 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
脚本2:CREATE_INDEXES.sql
[sql] view plain
copy
print?
- /* 创建索引 */
- 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
脚本3:CREATE_PROCEDURES.sql
[sql] view plain
copy
print?
- /* 创建存储过程 */
- 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
脚本4:CREATE_TABLES.sql
[sql] view plain
copy
print?
- /* 创建数据表 */
- 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
脚本5:TABLE_INSERTS.sql
[sql] view plain
copy
print?
- /* 插入表数据 */
-
- 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
第二步:在C盘根目录下创建一个bat文件create_db.bat,用于执行SQLCMD:
[plain] view plain
copy
print?
- SQLCMD -E -dmaster -ic:\Scripts\create_db.sql
- PAUSE
第三步:在C盘下直接执行bat文件:
双击文件可以看到:
在执行前,是没有TestDB:
执行中:
执行后,该创建的东西都创建出来了:
由于执行的顺序已经在脚本1中定义好,所以直接执行即可,并且执行成功。
总结:
根据个人经验,还是开发一个批量执行工具会比较好,这个方法在少量脚本的时候可以选用。
http://blog.csdn.net/dba_huangzj/article/details/8350829
使用SQLCMD在SQLServer执行多个脚本
标签:str insert 第三方 应对 view from pop create 定义