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

问题描述 投票:0回答:1

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

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

c# winforms sqlcommand
1个回答
3
投票

是的,创建一个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() );
}
© www.soinside.com 2019 - 2024. All rights reserved.