Stored Procedure argument “NULL” or “= NULL”

牧云@^-^@ 提交于 2020-06-27 08:17:19

问题


What is the difference between:

CREATE PROCEDURE [dbo].[MyProcedure] 
                @MyArgument INT NULL

and

CREATE PROCEDURE [dbo].[MyProcedure] 
                @MyArgument INT = NULL

I used the first one, and it worked fine in SQL Server 2016. But SQL Server 2012 did not accept it. Both works on SQL Server 2016, and I am using the second one now without problem. But it would be interesting to know the difference.

Thanks!


回答1:


They don't do the same thing. The second one defines a default value for the case that the caller doesn't specify one. The first one doesn't.

The "Transact-SQL Syntax for Natively Compiled Stored Procedures" grammar allows parameter datatypes to be declared as allowing NULL or NOT NULL. This was introduced for Hekaton (memory optimised tables).

Though it isn't documented as supported for the grammar in "Transact-SQL Syntax for Stored Procedures" it looks like it allows NULL but balks at NOT NULL and throws an error.

The parameter '@MyArgument' has been declared as NOT NULL. NOT NULL parameters are only supported with natively compiled modules, except for inline table-valued functions.

There is no value in specifying NULL explicitly - this is the default and only option. There is no declarative syntax for regular stored procs to indicate that parameters must be NOT NULL.




回答2:


They do different things:

1) @MyArgument INT NULL - NULL values are allowed for parameter @MyArgument

2) @MyArgument INT = NULL - Default value of parameter @MyArgument is NULL



来源:https://stackoverflow.com/questions/59422083/stored-procedure-argument-null-or-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!