为什么只更新了最后一条数据

xuyiwei2004 2011-02-19 10:28:28
test 表内共有 5条数据。为什么执行了以下代码只更新了最一个条数据。


declare @pos int

declare @len int

declare @str nvarchar(4000)

declare @des nvarchar(4000)

declare @count int

set @des ='a'--要替换的字符

set @len=len(@des)

set @str= 'b'--要替换成的值

set @count=0--统计次数.

WHILE 1=1

BEGIN

select @pos=patINDEX('%'+@des+'%',txt) - 1

from test --表名

where txt is not null

IF @pos>=0 -- 如果找到 要替换的字符 字符就执行下面的语句

begin

DECLARE @ptrval binary(16)

SELECT @ptrval = TEXTPTR(txt)

from test --表名

where txt is not null --条件

UPDATETEXT test.txt @ptrval @pos @len @str

set @count=@count+1

end

ELSE

break;

END

select @count

...全文
132 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
叶子 2011-02-19
  • 打赏
  • 举报
回复
[code=SQ]select @pos=patINDEX('%'+@des+'%',txt) - 1 from test [/code]
这是一个赋值,本身并不循环,上面while 1=1 这句话也是固定不变的。
快溜 2011-02-19
  • 打赏
  • 举报
回复
用循环不行,用游标试试。
快溜 2011-02-19
  • 打赏
  • 举报
回复
--这样就行了吧?
快溜 2011-02-19
  • 打赏
  • 举报
回复
[code=S]--[/code]
快溜 2011-02-19
  • 打赏
  • 举报
回复
[code=SQ][code=SQ]kk[/code][/code]
-晴天 2011-02-19
  • 打赏
  • 举报
回复
我靠!
[code=SQ][code=SQLL][/code]
-晴天 2011-02-19
  • 打赏
  • 举报
回复
[code=SQL]
-晴天 2011-02-19
  • 打赏
  • 举报
回复

[code=SQL]
--kkkk
[/code]
快溜 2011-02-19
  • 打赏
  • 举报
回复
。。
[code=SQ]
--kkkk
[/code]
快溜 2011-02-19
  • 打赏
  • 举报
回复
[code=SQ]
--可以用了?
[/code]
-晴天 2011-02-19
  • 打赏
  • 举报
回复
try:
create table test(txt nvarchar(100))
insert into test select 'kloweakdnalkaKD'
insert into test select 'onmsadjodaiad'
insert into test select 'vwioaujh'
insert into test select 'foimnsd'
go
declare @pos int
declare @len int
declare @str nvarchar(4000)
declare @des nvarchar(4000)
declare @count int
set @des ='a'--要替换的字符
set @len=len(@des)
set @str= 'b'--要替换成的值
set @count=0--统计次数.
while exists(select 1 from test where charindex(@des,txt)>0)
begin
update test set txt=stuff(txt,charindex(@des,txt),@len,@str) from test where charindex(@des,txt)>0
set @count=@count+@@ROWCOUNT
end
select @count
select * from test
go
drop table test
/*
-----------
7

(1 行受影响)

txt
----------------------------------------------------------------------------------------------------
klowebkdnblkbKD
onmsbdjodbibd
vwiobujh
foimnsd

(4 行受影响)

*/
/*
WHILE 1=1
BEGIN
select @pos=patINDEX('%'+@des+'%',txt) - 1
from test --表名
where txt is not null
IF @pos>=0 -- 如果找到 要替换的字符 字符就执行下面的语句
begin
DECLARE @ptrval binary(16)
SELECT @ptrval = TEXTPTR(txt)
from test --表名
where txt is not null --条件
UPDATETEXT test.txt @ptrval @pos @len @str
set @count=@count+1
end
ELSE
break;
END
select @count
*/

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧