简体   繁体   中英

How to dynamically provide column name and update the record in SQL Server?

I have a table like this

在此处输入图像描述

I want to store column name in varibale @myColumn and then use Update command. How can this be done? Is it possible?

    DECLARE @myColumn varchar(20)
    SET @myColumn = 'State'
    UPDATE Country SET @myColumn = 'Florida' WHERE Id = 1

Yes, it's possible with some dynamic SQL. If you have complete control in the process, you can try this solution:

Let's create a temp table to show:

create table #temp ([id] int, [state] varchar(10));

Insert into #temp
SELECT 1 as ID, null as [state]

select * from #temp

Now that's created, let's try

DECLARE @myColumn varchar(20), @sql varchar(400)
SET @myColumn = '[state]'

set @sql = CONCAT('Update #temp SET ',@myColumn ,'= ''FLORIDA'' where ID = 1')

exec(@sql)

Check the results

select * from #temp

If you don't have complete control over the process, you need to save your code from SQL Injection.

To dynamically use the name of a column you'll need Dynamic SQL.

Here's an example:

 DECLARE @DynSql nvarchar(max), @DynParams nvarchar(max), @UpdateSql nvarchar(max), @UpdateParams nvarchar(max); DECLARE @myColumn varchar(20), @myColumnValue varchar(20), @myId INT; SET @UpdateSql = 'UPDATE Country '+CHAR(10) + 'SET [COLUMN] = @Value' + CHAR(10) + 'WHERE Id = @Id'; SET @UpdateParams = N'@Value varchar(20), @Id int'; SET @myColumn = 'State'; SET @myColumnValue = 'Florida'; SET @myId = 1; SET @DynSql = REPLACE(@UpdateSql, '[COLUMN]', QUOTENAME(@myColumn)); SET @DynParams = @UpdateParams; -- select @DynSql As DynSql; EXECUTE sp_executesql @DynSql, @DynParams, @Value = @myColumnValue, @Id = @myId;
 1 rows affected 
SELECT * FROM Country WHERE ID = 1;
ID CountryName State
1 United States of America Florida

Demo on db<>fiddle here

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