如何在 SQL Server 2008 R2 数据库中制作 event/function 而不是 VBA 宏?

How to make event/function in SQL Server 2008 R2 database instead of VBA Macros?

我有一个 SQL Server 2008 R2 Express 数据库和一个 table。 Windows经验值。

我写了这个宏来请求 table 大小,如果 table 比我需要的大则删除行,我每 1 小时从 SCADA 调用 VBA。

Option Explicit
Dim strConn As String 
Dim strSQL As String 
Dim objConn As Object 
Dim objRecSet As Object 
Dim Command As Object 
Dim objRecSetValue as Double

On Error Resume Next
Err.Number = 0
strConn = "Provider=SQLOLEDB;Data Source=……….." 

Set objConn = CreateObject("ADODB.Connection")
objConn.ConnectionString = strConn
objConn.CursorLocation = 3
objConn.Open 

Set objRecSet = CreateObject("ADODB.Recordset")
Set Command = CreateObject("ADODB.Command")
Command.CommandType = 1
Set Command.ActiveConnection = objConn

strSQL = "SELECT SUM(a.total_pages) * 8 / 1024 AS TotalSpaceMB FROM sys.tables t "
strSQL = strSQL & "INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id "
strSQL = strSQL & "INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id "
strSQL = strSQL & "INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id "
strSQL = strSQL & "WHERE t.NAME LIKE 'Statistic' AND i.index_id <= 1 GROUP BY t.NAME "

Command.CommandText = strSQL
Set objRecSet = Command.Execute

objRecSet.MoveFirst
objRecSetValue = objRecSet.Fields(0).Value
objRecSet.Close

If objRecSetValue> 5000 then
    strSQL = "delete from dbo.statistic where dateandtime BETWEEN (SELECT MIN(dateandtime) FROM dbo.statistic) AND (SELECT MIN(dateandtime) FROM dbo.statistic) + 1"
Command.CommandText = strSQL
Set objRecSet = Command.Execute
End if

objConn.Close

ErrorHandler1:
Set Command = Nothing
Set objConn = Nothing
Set objRecSet = Nothing

现在我想避免 VBA,并在 SQL Server Management Studio (SSMS) 中创建 procedure/function,每 1 小时用 Windows Sheduler 和 sqlcmd 调用它, 但我不太了解 T-SQL 和 procedure/function 。有人可以帮助我在 T–SQL 中制作相同的代码吗? 谢谢

这是程序代码

CREATE PROCEDURE proPurgeTableData
AS
BEGIN TRY
    --variable for storing tablesize
    DECLARE @tablesizeMB    INT

    --setting size to variable
    SELECT 
        @tablesizeMB = SUM(a.total_pages) * 8 / 1024
    FROM 
        sys.tables t
        INNER JOIN sys.indexes i ON t.OBJECT_ID = i.object_id
        INNER JOIN sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
        INNER JOIN sys.allocation_units a ON p.partition_id = a.container_id
    WHERE 
        t.NAME LIKE 'Statistic' AND i.index_id <= 1 
    GROUP BY 
        t.NAME

    --if size greater than 5000 delete from table
    IF (ISNULL(@tablesizeMB,0)>5000)
    BEGIN
        BEGIN TRAN
            DELETE FROM dbo.statistic 
            WHERE dateandtime BETWEEN (SELECT MIN(dateandtime) FROM dbo.statistic) AND (SELECT MIN(dateandtime) FROM dbo.statistic) + 1
        COMMIT TRAN
    END
END TRY
BEGIN CATCH
    IF @@TRANCOUNT>0 ROLLBACK TRAN
END CATCH

您可以将其作为 EXEC proPurgeTableData 执行,只需将其添加到 sql 作业中即可。