简体   繁体   中英

SQL Server: update single columns within table

I have a large table with 20+ columns where I would only need to update 4 columns and keep the rest as is.

Is there a way I can achieve this with a stored procedure without having to pass the values for all columns? I am looking for something that says don't change this column and keep its content as is .

My stored procedure looks as like this ( col1 is an auto-incrementing ID that is set by the system):

CREATE PROCEDURE [dbo].[MySP]
    @col1 int,
    @col2 nvarchar(20),
    @col9 nvarchar(20),
    @col10 nvarchar(100)
AS
BEGIN
    SET NOCOUNT ON;
    UPDATE  MyTable
    SET col2 = @col2,
        col9 = @col9,
        col10 = @col10
    WHERE   col1 = @col1
END

Thanks for any help with this, Tim.

Or if it four different Columns everytime then you need to something like this..

CREATE PROCEDURE [dbo].[MySP]
@col1 int = null,
@col2 nvarchar(20) = null,
@col3 nvarchar(20) = null,
@col4 nvarchar(20) = null,
.
.
@col20 nvarchar(100) = null

AS
BEGIN
    SET NOCOUNT ON;
    UPDATE  MyTable
    SET  col2 = CASE WHEN @col2 IS NULL THEN col2 ELSE @col2 END
        ,col3 = CASE WHEN @col3 IS NULL THEN col3 ELSE @col3 END
        ,col4 = CASE WHEN @col4 IS NULL THEN col4 ELSE @col4 END
        ,....... 
        ,col20 = CASE WHEN @col20 IS NULL THEN col20 ELSE @col20 END
    WHERE   col1 = @col1
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM