日期:2014-05-19  浏览次数:20495 次

求一sql语句 或存储过程都行
表A中   有字段   A1,A2,A3,A4,A5

有两个参数     c和d
在表A中查寻如果在A2,A3,A4,A5中某一字段的值等于d就把等于d字段的前一个字段的值该为c
即     如过A5   =   D   就把A4该为c    
如过A4   =   D   就把A3该为c

------解决方案--------------------
create procedure protest
@c varchar(10)
@d varchar(10)
as
declare @i int
declare @s varchar(2000)
set @i=2
while @i <=5
begin
set @s= 'update tb set a '+cast(@i-1 as varchar)+ '= ' ' '+@c+ ' ' ' where a '+cast(@i as varchar)+ '= ' ' '+@d + ' ' ' '
exec(@s)
set @i=@i+1
end
------解决方案--------------------
没想到好办法~~~

CREATE TABLE A(A1 INT,A2 INT,A3 INT,A4 INT,A5 INT)
INSERT A(A1,A2,A3,A4,A5) SELECT 1,2,3,4,5
INSERT A(A1,A2,A3,A4,A5) SELECT 1,2,3,4,8
INSERT A(A1,A2,A3,A4,A5) SELECT 1,2,3,8,5

SELECT * FROM A
GO

CREATE PROC PU_A
@C INT,
@D INT
AS
BEGIN

UPDATE A SET A1=CASE WHEN A2=@D THEN @C ELSE A1 END,
A2=CASE WHEN A3=@D THEN @C ELSE A2 END,
A3=CASE WHEN A4=@D THEN @C ELSE A3 END,
A4=CASE WHEN A5=@D THEN @C ELSE A4 END

END
GO

EXEC PU_A NULL,8

SELECT * FROM A

DROP PROC PU_A
DROP TABLE A