SQL Server - sqlcmd example

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]
[-b On error batch abort]
[-v var = "value"...] [-A dedicated admin connection]
[-X[1] disable commands, startup script, enviroment variables [and exit]]
[-x disable variable substitution]
[-? show syntax summary]


#######################################
# Query data from a table
#######################################
C:\>sqlcmd -s localhost
1> use testdb
2> go
Changed database context to 'testdb'.
1> select num,cast(name as varchar(12)) as name,cast(orderno as varchar(20)) as
2> orderno from my_test_tab
3> go

num        name        orderno
----------- ------------ --------------------
1             John        100000001
2             Bob         100000002
3             Mary        100000003

(3 rows affected)


#######################################
# Export a table data to a CSV file
#######################################
# (Method 1):

sqlcmd -S 192.168.10.201 -U danbrother -P mypass -Q "set nocount on; set ansi_warnings off; select * from my_test_tab" -o D:\MSSQL_TO_CSV\my_test_tab.csv -h-1 -s"," -W -w 2000


# (Method 2):

sqlcmd -S 192.168.10.201 -U danbrother -P mypass -i D:\MSSQL_TO_CSV\my_test_tab.sql -o D:\MSSQL_TO_CSV\my_test_tab.csv -h-1 -s"," -W -w 2000

type D:\MSSQL_TO_CSV\my_test_tab.sql
set nocount on
set ansi_warnings off
select * from my_test_tab

 

[Reference]
http://technet.microsoft.com/zh-tw/library/ms180944.aspx

arrow
arrow
    全站熱搜

    DanBrother 發表在 痞客邦 留言(0) 人氣()