日期:2014-05-18  浏览次数:20669 次

在线等。。字段内容,作为列名来更新。。。
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
--> 测试数据:  TB
if object_id('TB') is not null drop table TB
GO
create table TB (ID int,colum int,[1] varchar(1),[2] varchar(1),[3] varchar(1))
insert into TB
select 1,3,'A','A','A' union all
select 1,1,'A','A','A' union all
select 1,2,'A','A','A' union all
select 1,1,'A','A','A'

DECLARE @S VARCHAR(1000),@COL INT



SELECT @S=ISNULL(@S,'')+'
UPDATE TB 
SET ['+LTRIM([COLUM])+']=''C'' WHERE COLUM='+LTRIM([COLUM])+';' FROM TB

--PRINT @S
EXEC(@S)

select * from  TB
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

(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 test
set [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' end

select * from test

/*查询更新结果*/
ID    column    1    2    3
1    3    A    A    C
1    1    C    A    A
1    2    A    C    A
1    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