在VB.NET中获得完整的SQL Azure数据库副本

时间:2016-02-24 14:23:45

标签: vb.net azure copy progress azure-sql-database

我需要帮助从Azure中的sys.dm_database_copies视图中获取percentage_complete值,以在我的VB.NET应用程序中填充WPF进度条控件。

这是我正在做的事情: 我有一个允许用户创建新帐户的窗口,该帐户将在Azure帐户中创建现有数据库的数据库副本,然后继续在该数据库的特定表中插入新记录。在复制数据库时,我想查询%complete,以便我可以为用户填充Progressbar值并知道它何时完成,这样我就可以继续使用" INSERT INTO"言。

这是我的代码(错误摘要):

Dim commandString = "CREATE DATABASE " & dbname.Text & " AS COPY OF DB1;"
'Creates a database copy
Using connection As New SqlConnection("Data Source=XXXXXX.database.windows.net,1433;Initial Catalog=master;Persist Security Info=True;User ID=UserID@;Password=XXXXXX")
    Dim command As New SqlCommand(commandString, connection)
    Try
        connection.Open()
        command.ExecuteNonQuery()
        connection.Close()
    Catch ex As Exception
        Throw ex
    End Try
End Using

'Check % complete
Dim pctValue As Double = 0
Dim timer1 As Double = Timer

'Create the SQL query
commandString = "SELECT percentage_complete FROM sys.dm_database_copies WHERE database_id = '" & dbname.Text & "';"

'Open the connection and keep it open to cycle until copy process is completed
Using connection As New SqlConnection("Data Source=XXXXXX.database.windows.net,1433;Initial Catalog=master;Persist Security Info=True;User ID=userID@XXXXXX;Password=XXXXXX")
    connection.Open()
    Dim command As New SqlCommand(commandString, connection)

    'Start a loop to query % complete and then wait 3 seconds and query again until % complete is >= 100 (100%)
    Do
        Try
            'Return the % complete (range of 0 to 100)
            pctValue = command.ExecuteScalar()
            'Set the Progressbar control value to the returned value
            PctComplete.Value = pctValue
        Catch ex As Exception
            Throw ex
        End Try

        timer1 = Timer
        Do : Loop Until Timer >= timer1 + 3
    Loop Until pctValue >= 100
    connection.Close()
End Using

'Set % complete to 100% to show it is truly complete to user
PctComplete.Value = 100

1 个答案:

答案 0 :(得分:0)

这不起作用的原因是因为一旦数据库副本完成就会删除此DMV中的行,因此它具有值100的持续时间非常短。考虑到视图每30秒更新一次,就不可能抓住那一刻。

此DMV适用于监控进度和构建进度条等,但遗憾的是不适合检测完成时刻。对于后者,我建议使用以下T-SQL:

SELECT * FROM sys.dm_operation_status
WHERE
    major_resource_id = 'dbname'
    AND operation = 'CREATE DATABASE COPY'
    AND state = 2
ORDER BY start_time DESC.