We want to change the way we pass values from PHP to stored procedures (T-SQL). I only have minor experience with PHP but I will attempt to explain the process from discussions with our web developer.
Current Process
Example test table
In order to update a record, such as Field3 in this example, we would pass all existing values back to the stored procedure.
EXEC dbo.UpdateTest @ID = 1, @Field1 = 'ABC', @Field2 = 'DEF', @Field3 = 'GHI', @Field4 = 'JKL'
Lets say to update Field3, you must click a button. This would navigate to a new page which would run the stored procedure to update the data. As the new page is unaware of the values it has to run a SELECT
procedure to retrieve the values before running an UPDATE
.
The script would then redirect the user back to the page which reloads the updated data and the changes are reflected on screen.
New Process
What we would like to do is only pass the fields we want to change.
EXEC dbo.UpdateTest @ID = 1, @Field2 = 'DEF', @Field3 = 'GHI'
Our solution is simple. First we set all of the updatable fields to optional (so NULL
can be passed). We then check to see if the parameter is NULL
(is not passed), if it is then we ignore it and if it isn't we update it.
UPDATE
dbo.Test
SET
Field1 = NULLIF(ISNULL(@Field1,Field1),'-999')
,Field2 = NULLIF(ISNULL(@Field2,Field2),'-999')
,Field3 = NULLIF(ISNULL(@Field3,Field3),'-999')
,Field4 = NULLIF(ISNULL(@Field4,Field4),'-999')
WHERE
ID = @ID
However we still want the procedure to update the database record to NULL
if a NULL
value is passed. The workaround for this was to assign an arbitrary value to equal NULL
(in this case -999), so that the procedure will update NULL
if the arbitrary value (-999) is passed.
This solution is rather messy and, in my eyes, an inefficient way of solving the problem. Are there any better solutions? What are we doing wrong?
A huge thanks in advance to any replies