日期:2014-05-18 浏览次数:20516 次
create table A(id int,psort int) insert into A select 10,0 insert into A select 11,0 insert into A select 13,0 declare @IDS varchar(20),@PSORTS varchar(20),@sql VARCHAR(1000) SELECT @IDS='55,44,10,13,15,90',@PSORTS='1,2,3,4,5,2' create table #t(id int identity(1,1),c2 int) select @sql= 'select '+replace(@psorts, ',', ' union all select ') insert into #t(c2) exec(@sql) update a set a.psort=c2 from a inner join #t t on len(@ids)-len(replace(@ids,',',''))+1 -len(stuff(@ids,1,charindex(','+rtrim(a.id)+',',','+@ids+',')+1,'')) +len(replace(stuff(@ids,1,charindex(','+rtrim(a.id)+',',','+@ids+',')+1,''),',','')) =t.id where charindex(','+rtrim(a.id)+',',','+@ids+',')>0 select * from a drop table A,#t
------解决方案--------------------
create procedure updateTableA @idS varchar(100), @psortS varchar(100) AS BEGIN Declare @spot1 int, @spot2 int, @id varchar(100), @psort varchar(100), @sql varchar(200) WHILE @idS <> '' AND @psortS <> '' Begin SET @spot1 = Charindex(',', @idS) SET @spot2 = Charindex(',', @psortS) if @spot1 > 0 AND @spot2 > 0 Begin SET @id = cast(left(@idS, @spot1-1) as int) SET @psort = cast(left(@psortS, @spot2-1) as int) set @idS = right(@idS, len(@idS)-@spot1) set @psortS = right(@psortS, len(@psortS)-@spot2) END ELSE Begin SET @id = cast(@idS as int) set @psort = cast(@psortS as int) set @idS = '' set @psortS = '' END SET @sql = 'UPDATE A SET psort = ' + @psort + ' WHERE id= ' + @id exec(@sql) END End drop table A create table A (id int, psort int) insert into A select 10,0 insert into A select 11,0 insert into A select 13,0 GO declare @idS varchar(100),@PSORTS varchar(100) set @idS= '10,13' set @PSORTS = '2,5' exec updateTableA @idS, @Psorts select * from A