开发者

Default null values in stored procedures are not Null

开发者 https://www.devze.com 2023-01-27 23:35 出处:网络
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...

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...

Create Procedure TestVarcharMaxIsNull
(@myVar varchar(MAX) = '')
as
Select 'Hello' Where @myVar Is Null
Go
Exec TestVarcharMaxIsNull Null
Go
Exec TestVarcharMaxIsNull ''
Go开发者_如何学C
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?


No, null values are not set to the default, as null is itself a valid value for a variable or field in 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

Where @myVar Is Null

will only evaluate to true when you explicitly pass in a null argument, as in your first test case.

0

精彩评论

暂无评论...
验证码 换一张
取 消