简体   繁体   English

存储过程中的默认null值不为Null

[英]Default null values in stored procedures are not Null

I have been testing a faulty procedure, and I realised that the problem is Null values being passed in are not being defaulted to the procedure value... 我一直在测试错误的过程,但我意识到问题是传入的Null值未默认为过程值...

Create Procedure TestVarcharMaxIsNull
(@myVar varchar(MAX) = '')
as
Select 'Hello' Where @myVar Is Null
Go
Exec TestVarcharMaxIsNull Null
Go
Exec TestVarcharMaxIsNull ''
Go
Exec TestVarcharMaxIsNull 
Go
Drop Procedure TestVarcharMaxIsNull

Output 输出量

Run 1 - "hello"
Run 2 - ""
Run 3 - ""

I assumed that Null values were defaulted to the value is assigned to in the stored procedure parameter, but this shows if it exists as a parameter it takes the value you pass in. Is there a setting in SQL server that can change this behaviour? 我假设Null值默认为在存储过程参数中分配的值,但是这表明它是否作为参数存在,并采用您传入的值。SQLServer中是否有可以更改此行为的设置?

No, null values are not set to the default, as null is itself a valid value for a variable or field in SQL. 不,空值未设置为默认值,因为空值本身是SQL中变量或字段的有效值。

To ensure a parameter gets its default value, do not pass in the parameter at all. 为确保参数获得其默认值,请不要传入任何参数。 So for your proc: 所以对于您的过程:

-- @myVar will get default
EXEC TestVarcharMaxIsNull 
-- @myVar will be null
EXEC TestVarcharMaxIsNull @myVar=NULL
-- @myVar will be "Hello"
EXEC TestVarcharMaxIsNull @myVar='Hello'

Default values as assigned only when you omit the parameter from the procedure call. 仅当您从过程调用中省略参数时,才分配默认值。 You can test if the parameter is null in the procedure and assign it the default value you want. 您可以在过程中测试参数是否为空,并为其分配所需的默认值。

declare @var varchar(MAX)
select @var = ISNULL(@myVAR, '')

The empty string '' is not equivalent to a null value. 空字符串“”不等于空值。

So where you say 所以你在哪里说

(@myVar varchar(MAX) = '')

means that when you don't pass in an argument you will get an empty string in @myVar, which in turn means that when you say 表示当您不传递参数时,您将在@myVar中获得一个空字符串,这又意味着当您说

Where @myVar Is Null

will only evaluate to true when you explicitly pass in a null argument, as in your first test case. 仅当您显式传递null参数时(如第一个测试用例),才会计算为true。

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

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