简体   繁体   English

在存储过程中接受NULL

[英]Accepting NULLS into Stored Procedures

I've got the below stored procedure that is very simple, but it allows NULL values to be passed in. 下面的存储过程非常简单,但是它允许传入NULL值。

I'm just wondering what best practice is here, and how to deal with NULLs in cases such as this? 我只是想知道这里有什么最佳实践,以及在这种情况下如何处理NULL?

ALTER PROCEDURE [dbo].[spGetClient]
    @ClientID int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        ......
    FROM
        Client
    WHERE
        ClientID = @ClientID

You can raise a custom error: 您可以引发自定义错误:

ALTER PROCEDURE [dbo].[spGetClient]
    @ClientID int
AS
BEGIN
    SET NOCOUNT ON;

    if @ClientID is null 
    BEGIN
          raiserror('The value for ClientID should not be null', 15, 1)
          return;
    END
    SELECT
        ......
    FROM
        Client
    WHERE
        ClientID = @ClientID
END

The simplest thing would be to just declare the argument as NOT NULL : 最简单的事情就是将参数声明为NOT NULL

ALTER PROCEDURE [dbo].[spGetClient] (
    @ClientID int NOT NULL
)
. . . 

However, that is not quite allowed for all stored procedures. 但是,并非所有存储过程都允许这样做。

Your stored procedure is fine. 您的存储过程很好。 If a NULL value is passed in, then it will return no rows. 如果传入NULL值,则将不返回任何行。 This seems reasonable, because ClientId is probably never NULL in the Client table, so I don't see a problem. 这似乎是合理的,因为ClientIdClient表中可能永远不会为NULL ,因此我看不到任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM