2022年4月28日

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的名稱。

  1. select @@SERVERNAME
  2.  

三、命令提示字元執行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數據的動作了。

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

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


四、其他sqlcmd指令

  1. sqlcmd
  2. -a packet_size
  3. -A (dedicated administrator connection)
  4. -b (terminate batch job if there is an error)
  5. -c batch_terminator
  6. -C (trust the server certificate)
  7. -d db_name
  8. -D
  9. -e (echo input)
  10. -E (use trusted connection)
  11. -f codepage | i:codepage[,o:codepage] | o:codepage[,i:codepage]
  12. -g (enable column encryption)
  13. -G (use Azure Active Directory for authentication)
  14. -h rows_per_header
  15. -H workstation_name
  16. -i input_file
  17. -I (enable quoted identifiers)
  18. -j (Print raw error messages)
  19. -k[1 | 2] (remove or replace control characters)
  20. -K application_intent
  21. -l login_timeout
  22. -L[c] (list servers, optional clean output)
  23. -m error_level
  24. -M multisubnet_failover
  25. -N (encrypt connection)
  26. -o output_file
  27. -p[1] (print statistics, optional colon format)
  28. -P password
  29. -q "cmdline query"
  30. -Q "cmdline query" (and exit)
  31. -r[0 | 1] (msgs to stderr)
  32. -R (use client regional settings)
  33. -s col_separator
  34. -S [protocol:]server[instance_name][,port]
  35. -t query_timeout
  36. -u (unicode output file)
  37. -U login_id
  38. -v var = "value"
  39. -V error_severity_level
  40. -w column_width
  41. -W (remove trailing spaces)
  42. -x (disable variable substitution)
  43. -X[1] (disable commands, startup script, environment variables, optional exit)
  44. -y variable_length_type_display_width
  45. -Y fixed_length_type_display_width
  46. -z new_password
  47. -Z new_password (and exit)
  48. -? (usage)

參考資料


沒有留言:

張貼留言