MS-SQL: Run a SQL Script on Database Server

MS-SQL: Run a SQL Script on Database Server

To run a SQL script on a Microsoft SQL Server database, you can use the sqlcmd utility. This utility allows you to execute SQL commands and scripts from the command line or from a batch file.

To run a SQL script using sqlcmd, follow these steps:

  1. Open a command prompt window.
  2. Change to the directory where your SQL script is located.
  3. Type the following command and press Enter:
re‮‬fer to:lautturi.com
sqlcmd -S server_name -d database_name -U username -P password -i script.sql

Replace server_name with the name of your SQL Server instance, database_name with the name of the database you want to connect to, username with your login username, and password with your login password. Replace script.sql with the name of your SQL script file.

This will connect to the specified SQL Server instance and database, authenticate using the specified username and password, and execute the SQL commands contained in the script file.

You can also use the -o option to specify an output file to which the results of the script should be written. For example:

sqlcmd -S server_name -d database_name -U username -P password -i script.sql -o output.txt

This will execute the SQL script and write the results to the output.txt file.

You can find more information about the sqlcmd utility and its options in the Microsoft documentation: https://docs.microsoft.com/en-us/sql/tools/sqlcmd-utility?view=sql-server-ver15

Keep in mind that you will need to have the sqlcmd utility installed on your system and have the appropriate permissions to connect to the SQL Server instance and database. You may also need to configure your firewall to allow connections to the SQL Server instance. Consult the documentation for your SQL Server installation for more information.

Created Time:2017-10-30 10:17:49  Author:lautturi