How to remotely control Microsoft SQL Server through code)

Source: Internet
Author: User
Tags sql 2008

Microsoft SQL Server has an SDK library that provides various commands equivalent to the Manager function. As long as the corresponding Dll is referenced, the corresponding commands can be executed (. SQL.

1. reference the corresponding DLL (version: SQL 2008)

REFERENCE The following DLL, where the file is located: Install Mssql directory + Microsoft SQL Server \ 100 \ SDK \ Assemblies

Microsoft. SqlServer. ConnectionInfo. dll
Microsoft. SqlServer. Dmf. dll
Microsoft. SqlServer. Management. Sdk. Sfc. dll
Microsoft. SqlServer. ServiceBrokerEnum. dll
Microsoft. SqlServer. Smo. dll
Microsoft. SqlServer. SqlClrProvider. dll
Microsoft. SqlServer. SqlEnum. dll

Ii. Method

# Region Execute file of SQL
Public bool ExecuteSqlFile (string userId, string password, string server, string file)
{
Bool result = true;
Try
{
String sqlConnectionString = string. Format ("server = {2}; database = master; uid = {0}; pwd = {1}", userId, password, server );

FileInfo fileInfo = new FileInfo (file );

StringBuilder script = new StringBuilder (fileInfo. OpenText (). ReadToEnd ());
SqlConnection conn = new SqlConnection (sqlConnectionString );

Microsoft. SqlServer. Management. Smo. Server sqlServer = new Microsoft. SqlServer. Management. Smo. Server (new Microsoft. SqlServer. Management. Common. ServerConnection (conn ));

SqlServer. ConnectionContext. ExecuteNonQuery (script. ToString ());
}
Catch
{
Result = false;
}
Return result;
}
# Endregion

You can reference this method to execute a file to a remote database. The reference method is as follows:

Result = executesqlfile (dbusername, dbpassword, dbserver, filename );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.