在SQL Server存储过程中使用检查约束

时间:2017-05-07 00:25:56

标签: sql sql-server stored-procedures

我想在存储过程中创建一个检查约束,其中发票日期不能在1990年1月1日之前完成,并且不能超过9999年12月31日。

现在我的SQL脚本设置如下:

CREATE PROCEDURE dbo.[getBalanceByDueDateRange]
    @MINDATE DATETIME = '1990-01-01 00:00:00',
    @MAXDATE DATETIME = '9999-12-31 00:00:00'
AS       
    SELECT  
        i.InvoiceID AS 'Invoice ID',
        v.VendorID AS 'Vendor ID',
        CONVERT(VARCHAR (12), i.InvoiceDueDate, 107) AS 'Invoice Due Date',
        ABS(i.InvoiceTotal - i.PaymentTotal) AS 'Balance'
    FROM 
        dbo.[Vendors] v
    INNER JOIN 
        dbo.[Invoices] i ON v.VendorID = i.VendorID
    WHERE   
        i.InvoiceDueDate BETWEEN ISNULL(@MINDATE, i.InvoiceDate) AND ISNULL(@MAXDATE, i.InvoiceDate)
    ORDER BY 
        i.InvoiceDueDATE ASC;

如果MINDATEMAXDATE不在该范围内,我希望它返回错误。我以为我可能不得不使用IF / ELSE语句,但还有另外一种方法,比如使用CHECK CONSTRAINT吗?存储过程确实有效(因为它什么都不返回),但我希望它更有效和专业。如果您有任何建议,我很乐意听到。

2 个答案:

答案 0 :(得分:0)

感谢戈登·林诺夫的建议,我想出来了,谢谢戈登!

CREATE PROCEDURE dbo.[getBalanceByDueDateRange]
    @MINDATE DATETIME   = '1990-01-01 00:00:00' 
,       @MAXDATE DATETIME   = '9999-12-31 00:00:00'
AS
IF @MINDATE < '1900-01-01 00:00:00'
RAISERROR ('Please Select a Valid Date',0,1)
ELSE IF  @MAXDATE > '9999-12-31 00:00:00'
RAISERROR ('Please Select a Valid Date',0,1)
ELSE IF @MINDATE > @MAXDATE
RAISERROR ('The Minimum Date can`t be later than the Maximum Date',0,1)
ELSE
SELECT  i.InvoiceID AS 'Invoice ID'
,       v.VendorID AS 'Vendor ID' 
,       CONVERT(VARCHAR (12),i.InvoiceDueDate,107)AS 'Invoice Due Date'
,       ABS(i.InvoiceTotal - i.PaymentTotal) AS 'Balance'
FROM dbo.[Vendors] v
INNER JOIN dbo.[Invoices] i ON v.VendorID = i.VendorID
WHERE   i.InvoiceDueDate BETWEEN ISNULL(@MINDATE, i.InvoiceDate) AND
        ISNULL(@MAXDATE, i.InvoiceDate)
ORDER BY i.InvoiceDueDATE ASC;

答案 1 :(得分:0)

您可以使用RaiseError并从过程返回,如下所示。正如布兰登所说,约束不是代码

CREATE PROCEDURE dbo.[getBalanceByDueDateRange]
        @MINDATE DATETIME   = '1990-01-01 00:00:00' 
,       @MAXDATE DATETIME   = '9999-12-31 00:00:00'
AS       
BEGIN
    IF @MINDATE > @MAXDATE 
    BEGIN
        RAISERROR('MinDate is greater than MaxDate', 20, -1)
        RETURN
    END
    SELECT  i.InvoiceID AS 'Invoice ID'
    ,       v.VendorID AS 'Vendor ID' 
    ,       CONVERT(VARCHAR (12),i.InvoiceDueDate,107)AS 'Invoice Due Date'
    ,       ABS(i.InvoiceTotal - i.PaymentTotal) AS 'Balance'
    FROM dbo.[Vendors] v
    INNER JOIN dbo.[Invoices] i ON v.VendorID = i.VendorID
    WHERE   i.InvoiceDueDate BETWEEN ISNULL(@MINDATE, i.InvoiceDate) AND
            ISNULL(@MAXDATE, i.InvoiceDate)
    ORDER BY i.InvoiceDueDATE ASC;
END