开发者

Ignoring statements based on null parameters in a stored procedure

开发者 https://www.devze.com 2023-01-25 12:14 出处:网络
I have a stored procedure that contains a bunch of parameters. They will never all contain values, some will be null.

I have a stored procedure that contains a bunch of parameters. They will never all contain values, some will be null.

How do I ignore these insert statements if the parameters are null?

Using firebug for firefox it is telling me that my database columns can't contain nulls, which is why I believe I have incorrectly coded this stored procedure (I am using jQuery ajax and a web service to communicate with this stored procedure).

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


This stored procedure shouldn't be trying to insert NULLs into any table. Your IF statements are preventing that. Are you sure the error message isn't telling you that the parameters can't be NULL? If so, the way to fix it is just to give the parameters default values:

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>

I'd also suggest explicitly declaring the size of all your varchar and decimal parameters as well, rather than relying on the defaults.

0

精彩评论

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