Ignoring statements based on null parameters in a stored procedure
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.
加载中,请稍侯......
精彩评论