如何在存储过程中设置整数类型参数的默认值?

时间:2013-12-02 17:22:43

标签: sql-server-2008 stored-procedures

我有一个存储的产品,如下所示。如果我修改了 IF (@id!=0)

IF (@id!=null)

当我传递200这样的id时,IF (@id!=null)将返回false,将执行插入部分。为什么?我应该修改@id as int=null@id as int=0吗?

ALTER PROCEDURE [dbo].[spname]
    -- Add the parameters for the stored procedure here
    @id as int=null,
    @vendorName as varchar(150)=null
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;


    IF (@id != 0) -- update
    BEGIN
        ...
    END
    ELSE -- insert
          BEGIN
    ... 
          END
END

2 个答案:

答案 0 :(得分:3)

在SQL中,您无法使用Null=运算符测试!=。您必须改为使用Is NullIs Not Null

ALTER PROCEDURE [dbo].[spname]
    -- Add the parameters for the stored procedure here
    @id as int = null,
    @vendorName as varchar(150) = null
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;


    IF @id Is Not Null -- update
    BEGIN
        ...
    END
    ELSE -- insert
    BEGIN
    ... 
    END
END

https://stackoverflow.com/a/9581790/124386

答案 1 :(得分:0)

在编写任何SP之前使用SET ANSI_NULLS OFF

或者

转到数据库属性>>选项,设置ANSI NULLS Enabled使其适用于所需的数据库。

IF(@ID != 0)可行。