忽略基于存储过程中的null参数的语句

时间:2010-11-18 09:37:16

标签: sql-server tsql stored-procedures

我有一个包含一堆参数的存储过程。它们永远不会包含值,有些将为null。

如果参数为null,如何忽略这些插入语句?

使用firebug for firefox它告诉我我的数据库列不能包含空值,这就是为什么我认为我错误地编码了这个存储过程(我使用jQuery ajax和web服务与这个存储过程进行通信)

ALTER PROCEDURE dbo.Vehicle_InsertAll
    @Make  varchar,
    @Model  varchar,
    @SubModel varchar,
    @Liter decimal,
    @Cylinder varchar,
    @Fuel varchar,
    @FuelDel varchar,
    @Asp varchar,
    @EngDesg varchar
AS
IF @Make IS NOT NULL
BEGIN
    INSERT INTO VehicleMakes (VehicleMake) VALUES(@Make)
    END
    IF @Model IS NOT NULL
    BEGIN
    INSERT INTO VehicleModels (Name) VALUES(@Model)
    END
    IF @SubModel IS NOT NULL
    BEGIN
    INSERT INTO VehicleSubModels (Name) VALUES(@SubModel)
    END
    IF @Liter IS NOT NULL
    BEGIN
    INSERT INTO VehicleLiters (Liters) VALUES(@Liter)
    END
    IF @Cylinder IS NOT NULL
    BEGIN
    INSERT INTO VehicleCylinders (Cylinders) VALUES(@Cylinder)
    END
    IF @Fuel IS NOT NULL
    BEGIN
    INSERT INTO VehicleFuel (FuelType) VALUES (@Fuel)
    END
    IF @FuelDel IS NOT NULL
    BEGIN
    INSERT INTO VehicleFuelDelivery (Delivery) VALUES (@FuelDel)
    END
    IF @Asp IS NOT NULL
    BEGIN
    INSERT INTO VehicleAspiration (Asp) VALUES (@Asp)
    END
    IF @EngDesg IS NOT NULL
    BEGIN
    INSERT INTO VehicleEngDesg (Designation) VALUES (@EngDesg)
    END

    RETURN

1 个答案:

答案 0 :(得分:0)

此存储过程不应尝试将NULL插入任何表中。您的IF语句阻止了这一点。您确定错误消息没有告诉您参数不能是NULL吗?如果是这样,修复它的方法就是给出参数默认值:

ALTER PROCEDURE dbo.Vehicle_InsertAll
    @Make  varchar = null,
    @Model  varchar = null,
    @SubModel varchar = null,
    @Liter decimal = null,
    @Cylinder varchar = null,
    @Fuel varchar = null,
    @FuelDel varchar = null,
    @Asp varchar = null,
    @EngDesg varchar = null
AS
<Stored Procedure Statements>

我还建议明确声明所有varchar和decimal参数的大小,而不是依赖于默认值。