我们可以 运行 索引重建或重组来自 C# winform 的命令吗?

Can we run index rebuild or reorganize commands from C# winform?

我想知道 运行 MS SQL 服务器索引是否可以从 c# winform 重建或重组操作?

我有一个使用重建和重组的脚本。现在我想 运行 通过单击按钮将整个脚本放在服务器数据库上。可能吗?或者管理命令只能来自 SSMS 运行?

是的,创建一个 SqlCommand 对象并适当地设置 CommandText

请注意,T-SQL 中的标识符不能被参数化,这意味着您可能必须使用动态 SQL(又名可能容易受到 SQL 注入攻击),所以要小心.

例如重建索引:

const String sql = @"
    ALTER INDEX PK_Employee_BusinessEntityID ON HumanResources.Employee REBUILD;
";

using( StringWriter log = new StringWriter() )
using( SqlConnection c = new SqlConnection( connectionString ) )
using( SqlCommand cmd = c.CreateCommand() )
{
    c.InfoMessage += ( s, e ) => log.WriteLine( e.Message );

    await c.OpenAsync().ConfigureAwait(false);

    cmd.CommandText = sql;

    await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);

    MessageBox.Show( "Done!\r\n" + log.ToString() );
}