我想知道是否可以从c#winform运行MS SQL Server索引重建或重新组织操作?
我有一个使用重建和重组的脚本。现在我想通过单击按钮在服务器数据库上运行整个脚本。可能吗?或者只能从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() );
}