简体   繁体   English

如何在 SQL 服务器中动态提供列名并更新记录?

[英]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.我想将列名存储在变量@myColumn中,然后使用Update命令。 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.是的,有一些动态 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.如果您无法完全控制该过程,则需要从 SQL 注入中保存您的代码。

To dynamically use the name of a column you'll need Dynamic SQL.要动态使用列的名称,您需要 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 1 行受影响
SELECT * FROM Country WHERE ID = 1;
ID ID CountryName国家的名字 State State
1 1 United States of America美国 Florida佛罗里达

Demo on db<>fiddle here关于db<>fiddle 的演示在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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