当前位置: 代码迷 >> Sql Server >> 。字段内容,作为列名来更新。
  详细解决方案

。字段内容,作为列名来更新。

热度:18   发布时间:2016-04-27 14:24:12.0
在线等。。字段内容,作为列名来更新。。。
ID colum 1 2 3 
1 3 A A A
1 1 A A A
1 2 A A A
1 1 A A A

根据colum 字段内容,作为表的列来更新。更新后结果为。

ID colum 1 2 3 
1 3 A A C
1 1 C A A
1 2 A C A
1 1 C A A

不能代码,sql能做到吗。在线等。。谢谢

------解决方案--------------------
记录少的时候适用
SQL code
--> 测试数据:  TBif object_id('TB') is not null drop table TBGOcreate table TB (ID int,colum int,[1] varchar(1),[2] varchar(1),[3] varchar(1))insert into TBselect 1,3,'A','A','A' union allselect 1,1,'A','A','A' union allselect 1,2,'A','A','A' union allselect 1,1,'A','A','A'DECLARE @S VARCHAR(1000),@COL INTSELECT @S=ISNULL(@S,'')+'UPDATE TB SET ['+LTRIM([COLUM])+']=''C'' WHERE COLUM='+LTRIM([COLUM])+';' FROM TB--PRINT @SEXEC(@S)select * from  TBID          colum       1    2    3----------- ----------- ---- ---- ----1           3           A    A    C1           1           C    A    A1           2           A    C    A1           1           C    A    A(4 行受影响)
------解决方案--------------------
探讨
js_szy 吃的好开心.

------解决方案--------------------
SQL code
/*创建临时表*/create table test(   ID int,   [column] int,   [1] nvarchar(1),   [2] nvarchar(1),   [3] nvarchar(1),)/*创建示例数据*/insert into test(ID,[column],[1],[2],[3]) values(1,3,'A','A','A')insert into test(ID,[column],[1],[2],[3]) values(1,1,'A','A','A')insert into test(ID,[column],[1],[2],[3]) values(1,2,'A','A','A')insert into test(ID,[column],[1],[2],[3]) values(1,1,'A','A','A')/*执行更新*/update testset [1]=case when [column]=1 then 'C' else 'A' end,[2]=case when [column]=2 then 'C' else 'A' end,[3]=case when [column]=3 then 'C' else 'A' endselect * from test/*查询更新结果*/ID    column    1    2    31    3    A    A    C1    1    C    A    A1    2    A    C    A1    1    C    A    A
------解决方案--------------------
SQL code
update TB set [1]= case when  colum=1 then 'C' else [1] end,[2]=case when  colum=2 then 'C' else [2] end,[3]=case when  colum=3 then 'C' else [3] end
  相关解决方案