sql语句来增加字符串位数
来源:百度知道 编辑:UC知道 时间:2024/09/22 21:36:24
用不用游标都可以,不用更简洁。
主要是用到一些字符串函数,如len--求字符串的长度,ltrim--去除字符串的前导空格 rtrim---去除字符串的尾部空格
方法一:直接用update语句
update employee set empno='000'+ltrim(rtrim(empno)) where len(ltrim(rtrim(empno)))=3
update employee set empno='00'+ltrim(rtrim(empno)) where len(ltrim(rtrim(empno)))=4
方法二:采用游标
declare cur scroll cursor for select empno from employee for update
open cur
declare @ex char(10)
fetch first from cur into @ex
while @@fetch_status=0
begin
if len(ltrim(rtrim(@ex)))=3
update employee set empno='000'+ltrim(rtrim(empno)) where current of cur
else
if len(ltrim(rtrim(@ex)))=4
update employee set empno='00'+ltrim(rtrim(empno)) where current of cur
fetch next from cur into @ex
end
close cur
deallocate cur
必须用游标吗?
给个取巧的方法供你参考
update [employee] set [empno]=right(cast([empno] as varchar)