请问,在SQL 2000数据库表中,现在有一列 <手机号码> ,当新增一行数据时,我想要系统自动把该列生成11位数字,前面两位是定的,后面9位随机的,是不是用户自定义函数来实现,这个函数应该如何写啊?请高手指点!例如:在表user中,当insert一条记录时,user.手机号码 = ‘自动生成的十一位号码’:
------解决方案--------------------
select 'aa ' + cast(cast(rand(4)*1000000000 as int) as varchar(9))
------解决方案--------------------
create view v_rand
as
select rand() as v_rand
alter function f_getnumber()
returns varchar(20)
as
begin
declare @returns varchar(20)
select @returns=right(convert(numeric(18,12),v_rand),10)
from v_rand
return @returns
end
declare @user table(id int,username varchar(10),number varchar(20))
insert into @user select 1, 'a ', '00 '+dbo.f_getnumber()
union all select 2, 'b ', '00 '++dbo.f_getnumber()
union all select 3, 'c ', '00 '++dbo.f_getnumber()
select * from @user
/*
id username number
----------- ---------- --------------------
1 a 006706304248
2 b 001742368123
3 c 001418905765
(所影响的行数为 3 行)
*/
------解决方案--------------------
'AB '+convert(Varchar(20),convert(INT,round(rand()*1000000000,0)))
直接把这段放入到默认值里就可以了
------解决方案--------------------
create table user1 (id int,username varchar(10),number VARCHAR(20) default( '00 '+dbo.f_getnumber()))
insert into user1(id,username) select 1, 'a '
UNION ALL SELECT 2, 'b '
UNION ALL SELECT 3, 'c '
SELECT * FROM USER1
/*
id username number
----------- ---------- --------------------
1 a 005178574958
2 b 008200390490
3 c 007094039484
(所影响的行数为 3 行)
*/