请问如何插入一定格式的字符串

[复制链接]
查看11 | 回复8 | 2011-11-1 16:21:15 | 显示全部楼层 |阅读模式
我将关键字设为varchar型,希望的到如"TH000001"-"TH000027"这样的值,在插入时生成,不知道在sql server 里有没有方法可以生成这样有格式的字串,还是需要在程序里设定好TH后有几位数字,然后判断补多少0......有没有比较简单的方法实现呀,谢谢
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
你可以參考這個帖子.
http://www.itpub.net/508332.html
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
谢谢,我看了一下,他的情况和我的不太一样,我的数字位数是固定的,不够时需要补零,这个该怎么办呀
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
哈哈,那不是更容易?
create table table3
(
a varchar(8)
)
insert into table3
select 'TH000001'
union
select 'TH000002'
select * from table3
insert into table3
select substring(max(a),1,2)+substring(convert(varchar(7),(cast(substring(max(a),3,len(max(a))) as int)+1000001)),2,7) from table3
select * from table3
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
最初由 killcode 发布
[B]谢谢,我看了一下,他的情况和我的不太一样,我的数字位数是固定的,不够时需要补零,这个该怎么办呀 [/B]

不够补零用Replicate函数加上字符串的基本函数就可以,非常简单的问题。
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
可以写个函数来处理
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
declare @Billcode nvarchar(20)

declare @TempCode nvarchar(20)

declare @billnum int

declare @Lenth int



set @lenth=12

set @BillCode='TH'

set @BillCode=Rtrim(@BillCode)

set @BillNum=9



set @lenth=@lenth-len(@Billnum)

set @TempCode=Replicate('0',@lenth)



set @Billcode = @Billcode +''+@tempcode+''+Ltrim(convert(char(20),@billnum))


print @Billcode
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层
把上面的的TH,9的值做为参数传进去就可以了!~
回复

使用道具 举报

千问 | 2011-11-1 16:21:15 | 显示全部楼层

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行