SQL Server stored procedure with optional parameters updates wrong columns

孤人 提交于 2019-12-10 14:53:38

问题


I have a (legacy) VB6 program that needs some work. I have a stored procedure that updates a table of vendors. In this particular form, I don't need to update the entire row, just 10 or so columns out of the 20ish.

Here is some pseudo code that works fine if I want to update the entire row:

CREATE PROCEDURE [dbo].[spUpdateVendor](
    @pID INT,
    @pVendorID varchar(254), 
    @pVendorName varchar(255),
    @pContact varchar(255),
    @pEmail varchar(255),
    ...)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON

DECLARE @ErrorMessage nvarchar(4000);

BEGIN TRY
-- Start the transaction
    BEGIN TRANSACTION
        UPDATE tblVendor
            SET
                [Vendor ID] = @pVendorID,
                [Vendor Name] = @pVendorName,
                [Contact] = @pContact,
                [email] = @pEmail
                ...
            WHERE
                [ID] = @pID
    COMMIT TRANSACTION;
END TRY

If I want to only update some of the columns with data here is the (pseudo) code I have been trying (attempt at using optional parameters):

CREATE PROCEDURE [dbo].[spUpdateVendor2](
    @pID INT,
    @pVendorID varchar(254) = NULL, 
    @pVendorName varchar(255) = NULL,
    @pContact varchar(255) = NULL,
    @pEmail varchar(255) = NULL,
    ...)
AS
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON

DECLARE @ErrorMessage nvarchar(4000);

BEGIN TRY
-- Start the transaction
    BEGIN TRANSACTION
        UPDATE tblVendor
            SET
                [Vendor ID] = ISNULL(@pVendorID,[Vendor ID]),
                [Vendor Name] = ISNULL(@pVendorName,[Vendor Name]),
                [Contact] = ISNULL(@pContact,[Contact]),
                [Email] = ISNULL(@pEmail,[email]),
                ...
            WHERE
                [ID] = @pID 
    COMMIT TRANSACTION;
END TRY

and it all runs w/o errors but it will update the wrong column if I update one optional column, skip a few, then update another optional column.

Example of update using normal parameters:

tblVendor
ID: 2924
Vendor ID: Company1
Vendor Name: Company Name
Contact: Bob
email: bob@company.com

Example of updating via the optional parameters when I don't supply 'contact':

tblVendor
ID: 2924
Vendor ID: Company1
Vendor Name: Company Name
Contact: bob@company.com
email: bob@company.com

SO it updates the row, but it updates the wrong column. What am I doing incorrectly?


回答1:


You have to explicitly specify parameter names when executing stored procedure and pass in null for those you want to leave out. Example

exec spUpdateVendor2 @pID=102, @pVendorID = 1, @pVendorName = NULL, @pContact = 'Contact',
@pEmail = NULL ...


来源:https://stackoverflow.com/questions/13058891/sql-server-stored-procedure-with-optional-parameters-updates-wrong-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!