I'm trying to use simple CLR Function to backup sql database.
[SqlFunction(DataAccess = DataAccessKind.Read)]
public static int BackupDb()
{
using (var conn = new SqlConnection("context connection=true"))
{
conn.Open();
var cmd = new SqlCommand(
@"backup database MyDatabase to disk='d:\temp\MyDatabase.bak' WITH INIT, STATS=10", conn);
cmd.ExecuteNonQuery();
}
return 0;
}
But this code gives exception
Msg 6522, Level 16, State 1, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "BackupDb":
System.Data.SqlClient.SqlException: Invalid use of a side-effecting operator 'BACKUP DATABASE' within a function.
System.Data.SqlClient.SqlException:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQuerySmi(Boolean sendToPipe)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at UserDefinedFunctions.BackupDb()