SQL存储过程中发送电子邮件时出现语法错误?

时间:2014-05-22 15:29:19

标签: sql-server tsql email stored-procedures

您好我已经编写了一个存储过程来检索有关空间不足的服务器磁盘驱动器的信息。现在我只是尝试编写另一个存储过程来发送电子邮件通知,以通知客户端服务器磁盘空间不足。这就是我所拥有的:

--Creating alert notification
CREATE PROC dbo.sp_drivespacelow1_alerts
        @from varchar(100),
        @to varchar(200),
        @subject varchar(100),
        @threshold int  -- number of MB under which to launch an alert
AS

        SET NOCOUNT ON

        DECLARE @list nvarchar(2000) = '';

        WITH core AS ( 
                SELECT DISTINCT
                        s.volume_mount_point [Drive],
                        CAST(s.available_bytes / 1048576 as decimal(12,2))      [AvailableMBs]
                FROM 
                    sys.master_files f
                       CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.[file_id]) s
    )

        SELECT @list = @list + ' ' + Drive + ', '
        FROM core
        WHERE AvailableMBs < @threshold

        IF LEN(@list) > 3 BEGIN
                DECLARE @msg varchar(500) = 'Low Disk Space Notification. The following     drives are currently reporting less than ' 
                + CAST(@threshold as varchar(12)) + ' MB free: ' + @list

                EXEC msdb.dbo.sp_send_dbmail @profile_name = 'xxxxx',
                @recipients = @to,
                @subject = @subject,
                @body = @msg

        END

        RETURN 0
GO --Check done every 5 mins

--To Run:
EXEC master.dbo.sp_drivespace_alerts
      @threshold = 5120 --5 GB
      @from = 'sqlalert@noreply.com'
      @subject = 'Low diskspace alert -ServerName Here'
      @to = 'marakelly84@yahoo.ie'

以下是我用来检查磁盘空间的内容:

--Returns informations on drives with less than 5 GBs of disk space
CREATE TABLE #drives (
        drive char,
        [free] int
)

INSERT INTO #drives
EXEC master..xp_fixeddrives

SELECT drive, [free] 
FROM #drives 
WHERE [free] < 5 * 102 

drop table #drives --must get rid of temporary tables in order to run again

现在检查磁盘空间的存储过程很好,但发送电子邮件通知的存储过程一直给我回复此错误: 消息2714,级别16,状态3,过程sp_drivespacelow_alerts,第37行 已有一个名为&#39; sp_drivespacelow_alerts&#39;在数据库中。 Msg 102,Level 15,State 1,Line 6 &#39; @来自&#39;,&#39; @ subject&#39;

附近的语法不正确

如果我注释掉这两行代码并运行此错误: Msg 102,Level 15,State 1,Line 7 &#39; @到&#39;。

附近的语法不正确

请帮助谢谢!

1 个答案:

答案 0 :(得分:-1)

如果你正在运行:

--To Run:
EXEC master.dbo.sp_drivespace_alerts
      @threshold = 5120 --5 GB
      @from = 'sqlalert@noreply.com'
      @subject = 'Low diskspace alert -ServerName Here'
      @to = 'marakelly84@yahoo.ie'

我想你想这样做:

--To Run:
CALL master.dbo.sp_drivespace_alerts (
      5120, --5 GB
      'sqlalert@noreply.com',
      'Low diskspace alert -ServerName Here',
      'marakelly84@yahoo.ie');