Search code examples
automationazure-sql-databaseazure-automationazure-runbook

Need help me with azure runbooks?


I want to schedule a simple task to truncate a table using the Runbook. The database is Azure SQL Database.

  • What type of runbook should I create. How should I code it?
  • Are there any sources to learn more about azure runbooks?

Solution

  • In your case, you could create a powershell runbook to execute TRUNCATE TABLE.

    To invoke sql command via powershell, you could refer to this link.

    Sample:

    function Invoke-SQL {
        param(
            [string] $dataSource = ".\SQLEXPRESS",
            [string] $database = "MasterData",
            [string] $sqlCommand = $(throw "Please specify a query.")
          )
    
        $connectionString = "Data Source=$dataSource; " +
                "Integrated Security=SSPI; " +
                "Initial Catalog=$database"
    
        $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
        $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
        $connection.Open()
    
        $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
        $dataset = New-Object System.Data.DataSet
        $adapter.Fill($dataSet) | Out-Null
    
        $connection.Close()
        $dataSet.Tables
    
    }
    

    For more details about Azure runbook, you could refer to this doc.