Sql server SQL中的复合update语句
我不知道该怎么做-- 我有一个本地表,其中包含需要更新的字段Sql server SQL中的复合update语句,sql-server,join,sql-update,multiple-columns,Sql Server,Join,Sql Update,Multiple Columns,我不知道该怎么做-- 我有一个本地表,其中包含需要更新的字段 select column_835 1, column_836 = 6, column_837 = 8, column_838 = 1, column_839 = 6, column_840 = 3, column_841 = 6, column_842 = 8 from #esp 更新语句如下所示-- 发生的情况是,我想用本地表中的值更新行“column835”,其中颜色为
select column_835 1,
column_836 = 6,
column_837 = 8,
column_838 = 1,
column_839 = 6,
column_840 = 3,
column_841 = 6,
column_842 = 8
from #esp
更新语句如下所示--
发生的情况是,我想用本地表中的值更新行“column835”,其中颜色为蓝色
第二个查询将使用百分比值更新“column837”,但该值对应于绿色,以此类推。我想做的是了解如何生成一个update语句,而不是8个或更多。(如果添加更多颜色,我们必须在代码中进行更多更新)
如何使用
so for example
column_835 = percent (but only where b.color = blue)
column_837 = percent (but only where b.color = green)
column_842 = percent (but only where b.color = white)
and so on.
数据来自下面-- 我还有第二张表,上面有这样的数据
select *
from T_VALUES v
where v.column_id = 728
列_id 728的表'values'中的数据返回如下
id keyword_no key_value
840 728 red
839 728 white
837 728 green
835 728 blue
841 728 yellow
838 728 black
842 728 white
836 728 purple
您可以使用
case
update a
set
column_835 = (CASE WHEN b.color='blue' THEN (b.percent) Else column_835 End),
column_837 = (CASE WHEN b.color='green' THEN (b.percent) Else column_837 End),
column_842 = (CASE WHEN b.color='white' THEN (b.percent) Else column_842 End)
from #esp a
join #local_data b on a.c_no = b.c and a.fyear = b.fyear
如果@color是一个输入参数,请尝试以下操作
DECLARE @id NVARCHAR(10)
SELECT
@id = CAST(Id AS NVARCHAR(10))
FROM
T_VALUES v
WHERE
v.column_id = 728
AND
key_value = @Colour
--Dynamic SQL part
DECLARE @SQL NVARCHAR(MAX)
SET @SQL =
'
update a
set column_' + @id + ' = b.percent
from #esp a
join #local_data b on a.c_no = b.c and a.fyear = b.fyear
where b.color = ''' + @Colour + '''
' ;
--PRINT @SQL
EXEC sys.sp_executesql @SQL ;
为什么不将存储的Proc与动态SQL@Cool_Br33ze我正在编写一个过程(这就是update语句所包含的内容)以及大部分代码。但是列已经预先确定,不能更改。我只是不知道如何编写一条update语句来智能地更新所有的行,而不是8条update语句。这看起来很棒,我不知道为什么想不出case语句。implementing now.my结果集有5行,其中联接匹配,但列_835仅在其中一行中更新。我需要它来更新每一行。我不知道为什么它不起作用。你应该删除“蓝色”的where子句。你是什么意思。什么时候把那部分拿出来?很抱歉造成混淆,我的意思是,您最初的查询有“where b.color='blue'”。你把它拿走了吗?
DECLARE @id NVARCHAR(10)
SELECT
@id = CAST(Id AS NVARCHAR(10))
FROM
T_VALUES v
WHERE
v.column_id = 728
AND
key_value = @Colour
--Dynamic SQL part
DECLARE @SQL NVARCHAR(MAX)
SET @SQL =
'
update a
set column_' + @id + ' = b.percent
from #esp a
join #local_data b on a.c_no = b.c and a.fyear = b.fyear
where b.color = ''' + @Colour + '''
' ;
--PRINT @SQL
EXEC sys.sp_executesql @SQL ;
update a
set column_835 = (select b.percent from #local_data b where color ='blue' and b.fyear = a.fyear and b.c = a.c_no),
column__837 = (select b.percent from #local_data b where color= 'green' and b.fyear = a.fyear and b.c = a.c_no),
column_y_842 = (select b.percent from #local_data b where color= 'white' and b.fyear = a.fyear and b.c = a.c_no)
from #esp a