Monday, August 4, 2014

Execute Sql Commands through Command Prompt

Here I am sharing that how can we execute SQL Commands through Command Prompt.

Using this command line utility, we can also fire queries and execute files, etc.

Sample Syntax:

SqlCmd -S servername -U "username" -P "password" -q "sql command"

 

Ex.

SqlCmd -E -S 192.168.0.1\Sql2008 -Q "BACKUP DATABASE Practice TO Disk='C:\dbbackups\db_Practice.bak';BACKUP LOG Practice TO Disk='C:\dbbackups\db_Practice.bak';"

 

SqlCmd -S 192.168.0.1\Sql2008 -U "sa" -P "sa@123" -q "RESTORE DATABASE Practice FROM DISK = 'e:\Backups\db_Practice.bak' WITH MOVE 'Practice' TO 'G:\DBBackups\Practice.mdf',MOVE 'Practice_log' TO 'G:\DBBackups\Practice.ldf';"

 

For more options check below detail:

 

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 

   -e (echo input)

   -E (use trusted connection)

   -f codepage | i:codepage[,o:codepage] | o:codepage[,i:codepage]

   -h rows_per_header 

   -H workstation_name 

   -i input_file 

   -I (enable quoted identifiers)

   -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 and optional exit)

   -y variable_length_type_display_width 

   -Y fixed_length_type_display_width 

   -z new_password  

   -Z new_password (and exit)

 

   -? (usage)

 

 

For Detail about "SqlCmd" Visit: http://msdn.microsoft.com/en-us/library/ms162773.aspx


ITWORLD
If you have any question then you put your question as comments.

Put your suggestions as comments