在SQLServer數據庫當中,除了大家熟知的基於SSMS來管理SQLserver數據庫之外,還有一個很強大的命令行工具sqlcmd。該命令行工具基本等同於Oracle SQL*Plus以及 MySQL命令提示符下以實現相關的運維管理工作。尤其是需要多個腳本執行的時候,sqlcmd便派上用場了。本文描述了sqlcmd的一些常規用法以及給出如何通過批處理方式執行腳本的示例。
一、獲取sqlcmd幫助
C:\>sqlcmd -? Microsoft (R) SQL Server Command Line Tool Version 12.0.2000.8 NT %當前版本為SQLserver2014 12.0% Copyright (c) 2014 Microsoft. All rights reserved. usage: Sqlcmd [-U login id] [-P password] [-S server] [-H hostname] [-E trusted connection] [-N Encrypt Connection][-C Trust Server Certificate] [-d use database name] [-l login timeout] [-t query timeout] [-h headers] [-s colseparator] [-w screen width] [-a packetsize] [-e echo input] [-I Enable Quoted Identifiers] [-c cmdend] [-L[c] list servers[clean output]] [-q "cmdline query"] [-Q "cmdline query" and exit] [-m errorlevel] [-V severitylevel] [-W remove trailing spaces] [-u unicode output] [-r[0|1] msgs to stderr] [-i inputfile] [-o outputfile] [-z new password] [-f <codepage> | i:<codepage>[,o:<codepage>]] [-Z new password and exit] [-k[1|2] remove[replace] control characters] [-y variable length type display width] [-Y fixed length type display width] [-p[1] print statistics[colon format]] [-R use client regional setting] [-K application intent] [-M multisubnet failover] [-b On error batch abort] [-v var = "value"...] [-A dedicated admin connection] [-X[1] disable commands, startup script, environment variables [and exit]] [-x disable variable substitution] [-? show syntax summary]
二、最常用的選項
服務器選項(-S),用於標識 sqlcmd 連接到的 Microsoft SQL Server 實例。 身份驗證選項(-E、-U 和 -P),用於指定 sqlcmd 連接到 SQL Server 實例所使用的憑據。-E 選項為默認選項,毋須指定。 輸入選項(-Q、-q 和 -i),用於標識 sqlcmd 輸入的位置。 輸出選項 (-o),用於指定 sqlcmd 輸出所在的文件。
三、常見用法
使用 Windows 身份驗證連接到默認實例,以交互方式運行 Transact-SQL 語句: sqlcmd -S <ComputerName> 上述示例中,未指定 -E,因為它是默認選項,而且 sqlcmd 使用 Windows 身份驗證連接到默認實例。 使用 Windows 身份驗證連接到命名實例,以交互方式運行 Transact-SQL 語句: sqlcmd -S <ComputerName>\<InstanceName> 或者 sqlcmd -S .\<InstanceName> 使用 Windows 身份驗證連接到命名實例,並指定輸入和輸出文件: sqlcmd -S <ComputerName>\<InstanceName> -i <MyScript.sql> -o <MyOutput.rpt> 使用 Windows 身份驗證連接到本地計算機上的默認實例,執行查詢,並在查詢運行完畢后使 sqlcmd 保持運行狀態: sqlcmd -q "SELECT * FROM AdventureWorks2012.Person.Person" 使用 Windows 身份驗證連接到本地計算機上的默認實例,執行查詢,將輸出定向到某個文件,並在查詢運行完畢后使 sqlcmd 退出: sqlcmd -Q "SELECT * FROM AdventureWorks2012.Person.Person" -o MyOutput.txt 使用 SQL Server 身份驗證連接到命名實例,以交互方式運行 Transact-SQL 語句,並由 sqlcmd 提示輸入密碼: sqlcmd -U MyLogin -S <ComputerName>\<InstanceName>
四、交互用法
交互方式,在請在未使用 -Q、-q、-Z 或 -i 選項指定任何輸入文件或查詢的情況下運行實用工具。 例如:sqlcmd -S <ComputerName>\<InstanceName> 交互方式2個常用的命令 GO + Enter : 將語句發送到SQLserver服務器並執行 Exit 或 QUIT : 退出sqlcmd命令行工作方式 :REST : 清除語句緩存,鍵入 ^C 將使 sqlcmd 退出,在發出 GO 命令后,還可以用 ^C 停止語句緩存的執行。 :ED : 使用編輯器編寫SQL 示例 C:\>sqlcmd -U sa -P Sqlserve -H HQ1636 1> use testdb; 2> go 已將數據庫上下文更改為 'testdb'。 1> select * from t2; 2> go id id2 ename ----------- ----------- ------------------- 1 1 NULL 1 NULL NULL 1 2 John (3 rows affected) 1> exit
五、使用sqlcmd運行SQL腳本
這個是比較管用的。對於熟悉Oracle SQL*Plus或者MySQL命令行的童鞋來說,有這個工具執行腳本,尤其是多個腳本需要執行的情緒,那個爽啊,不說了,直接看用法。
1、執行單個腳本
腳本內容如下 C:\>type E:\temp\Testsql.sql USE testdb; GO SELECT * FROM t2; GO 執行腳本 C:\>sqlcmd -U sa -P Sqlserve -H HQ1636 -i E:\temp\Testsql.sql -o E:\temp\Testresult.txt C:\>type E:\temp\Testresult.txt 已將數據庫上下文更改為 'testdb'。 id id2 ename ----------- ----------- -------------------- 1 1 NULL 1 NULL NULL 1 2 John (3 rows affected)
2、通過專用管理連接使用sqlcmd
下面使用專用連接方式殺死特定的session
C:\>sqlcmd -U sa -P Sqlserve -H HQ1636 -A 1> SELECT blocking_session_id FROM sys.dm_exec_requests WHERE blocking_session_id<>0; 2> go blocking_session_id ------------------- 54 (1 rows affected) 1> kill 54; 2> go
3、使用 sqlcmd 執行存儲過程
C:\>type E:\temp\TestProc.sql CREATE PROC proc_query_t2 @ename VARCHAR(20) AS SELECT * FROM t2 WHERE ename = @ename; GO C:\>sqlcmd -U sa -P Sqlserve -H HQ1636 -i E:\temp\TestProc.sql C:\>sqlcmd -U sa -P Sqlserve -H HQ1636 1> :setvar ename robin 1> exec testdb.dbo.proc_query_t2 $(ename) 2> go id id2 ename ----------- ----------- -------------------- 1 1 Robin (1 rows affected)
4、使用 sqlcmd 進行數據庫日常管理
C:\>type E:\temp\DB_bak.sql USE master; GO BACKUP DATABASE [$(db)] TO DISK='$(bakfile)' C:\>sqlcmd -U sa -P Sqlserve -H HQ1636 1> :setvar db testdb 1> :setvar bakfile e:\temp\testdb01.bak 1> :r e:\temp\DB_bak.sql 已將數據庫上下文更改為 'master'。 1> go 已為數據庫 'testdb',文件 'testdb' (位於文件 1 上)處理了 368 頁。 已為數據庫 'testdb',文件 'testdb_log' (位於文件 1 上)處理了 5 頁。 BACKUP DATABASE 成功處理了 373 頁,花費 0.377 秒(7.729 MB/秒)。
5、sqlcmd 對多個實例執行代碼
2> :connect 192.168.1.194 -U robin -P xx Sqlcmd: Successfully connected to server '192.168.1.194'. 1> select getdate() 2> go ----------------------- 2016-03-17 13:31:16.390 (1 rows affected) 1> :connect 192.168.1.207,2433 -U sa -P 123 Sqlcmd: Successfully connected to server '192.168.1.207,2433'. 1> select getdate() 2> go ----------------------- 2016-03-17 13:32:25.787 (1 rows affected)
6、使用批處理方式執行任務
這個對於運維的童鞋來說實在是幸福,可以將腳本封裝到批處理.bat文件以及加到windows計划任務。 C:\>type e:\temp\batch.bat @echo off sqlcmd -U sa -P Sqlserve -H HQ1636 -i e:\temp\all.sql -b -o e:\temp\out.log C:\>type e:\temp\all.sql :r e:\temp\driver.sql :r e:\temp\hostinfo.sql C:\>type e:\temp\hostinfo.sql PRINT 'Below is host info.'; PRINT '================================='; USE [master]; GO EXEC xp_msver; GO C:\>type e:\temp\driver.sql PRINT 'Below is drive info.'; PRINT '================================='; USE master; GO EXEC xp_fixeddrives; GO C:\>e:\temp\batch.bat %執行批處理腳本% Below is drive info. ================================= 已將數據庫上下文更改為 'master'。 drive MB 可用空間 ----- ----------- C 99784 D 138623 E 26783 F 217172 (4 rows affected) Below is host info. ================================= 已將數據庫上下文更改為 'master'。 Index Name Internal_Value Character_Value ------ -------------------------------- -------------- -------------------------------------------------- 1 ProductName NULL Microsoft SQL Server 2 ProductVersion 786432 12.0.2000.8 3 Language 2052 中文(簡體,中國) 4 Platform NULL NT x64 5 Comments NULL SQL 6 CompanyName NULL Microsoft Corporation 7 FileDescription NULL SQL Server Windows NT - 64 Bit 8 FileVersion NULL 2014.0120.2000.08 ((SQL14_RTM).140220-1752) 9 InternalName NULL SQLSERVR 10 LegalCopyright NULL Microsoft Corp. All rights reserved. 11 LegalTrademarks NULL Microsoft SQL Server is a registered trademark 12 OriginalFilename NULL SQLSERVR.EXE 13 PrivateBuild NULL NULL 14 SpecialBuild 131072008 NULL 15 WindowsVersion 131072008 6.1 (7601) 16 ProcessorCount 4 4 17 ProcessorActiveMask NULL f 18 ProcessorType 8664 NULL 19 PhysicalMemory 16297 16297 (17088618496) 20 Product ID NULL NULL
————————————————
原文鏈接:https://blog.csdn.net/leshami/java/article/details/50913475