聲命好好玩

分享生活,很多時候,我們都是在經歷別人走過的路,希望我走過的路,可以給予你們一些參考。

MS SQL server .sql指令檔案文件過大(sqlcmd)

最近使用.sql指令碼文件還原資料表結構與數據,但因為數據過多.sql檔案高達2G多,導致SQL server無法直接開啟檔案

爬了一些文章,找到使用Windows cmd 中的指令 sqlcmd可以直接執行.sql檔,把數據寫到資料庫中。


一、系統環境

SQL Server版本:Microsoft SQL server 2017 Express

SQL Server安裝位置:本機 127.0.0.1(localhost)


二、取得Server Name

在查詢框中輸入以下代碼,執行後可以取得當前SQL server的名稱。

select @@SERVERNAME


三、命令提示字元執行sqlcmd指令

請使用【以系統管理員身分執行】命令提示字元

我們先使用-S 指令與資料庫建立連線,再執行.sql文件

微軟官網語法說明如下

-S [protocol:]server[ \ instance_name][ , port]
指定要連線的 SQL Server 執行個體。 它會設定 sqlcmd 指令碼變數 SQLCMDSERVER。

指定 server_name,即可連線至該伺服器電腦上之 SQL Server 的預設執行個體。 指定 server_name [ \ instance_name ],即可連線到該伺服器電腦上 SQL Server 的具名執行個體。 如果未指定伺服器電腦,sqlcmd 會連線到本機電腦上 SQL Server 的預設執行個體。 當您從網路的遠端電腦執行 sqlcmd 時,需要這個選項。

protocol 可以是 tcp (TCP/IP)、 lpc (共用記憶體) 或 np (具名管道)。

如果您啟動 sqlcmd 時,並未指定 server_name [ \ instance_name ],SQL Server 會檢查並使用 SQLCMDSERVER 環境變數。


記得確認Sql server的服務是有啟動的。


接著請在命令提示字元視窗中輸入以下格式的指令,並按下Enter,就會開始自動執行建表與insert數據的動作了。

sqlcmd -S SQL的servername -i .sql的文件路徑
sqlcmd -S xxxx\SQLEXPRESS -i D:\xxxx\SPRINT4\dbo.INVMB.Table.sql

等跑完,資料表與數據就都建好囉。


四、其他sqlcmd指令

sqlcmd
   -a packet_size
   -A (dedicated administrator connection)
   -b (terminate batch job if there is an error)
   -c batch_terminator
   -C (trust the server certificate)
   -d db_name
   -D
   -e (echo input)
   -E (use trusted connection)
   -f codepage | i:codepage[,o:codepage] | o:codepage[,i:codepage]
   -g (enable column encryption)
   -G (use Azure Active Directory for authentication)
   -h rows_per_header
   -H workstation_name
   -i input_file
   -I (enable quoted identifiers)
   -j (Print raw error messages)
   -k[1 | 2] (remove or replace control characters)  
   -K application_intent  
   -l login_timeout  
   -L[c] (list servers, optional clean output)  
   -m error_level  
   -M multisubnet_failover  
   -N (encrypt connection)  
   -o output_file  
   -p[1] (print statistics, optional colon format)  
   -P password  
   -q "cmdline query" 
   -Q "cmdline query" (and exit)  
   -r[0 | 1] (msgs to stderr)  
   -R (use client regional settings)  
   -s col_separator  
   -S [protocol:]server[instance_name][,port]  
   -t query_timeout  
   -u (unicode output file)  
   -U login_id  
   -v var = "value"
   -V error_severity_level
   -w column_width
   -W (remove trailing spaces)
   -x (disable variable substitution)
   -X[1] (disable commands, startup script, environment variables, optional exit)
   -y variable_length_type_display_width
   -Y fixed_length_type_display_width
   -z new_password
   -Z new_password (and exit)
   -? (usage)

參考資料