菜鸟问题,SQL自增主键,无法用函数生成

cloudburst 2006-04-03 09:30:09
我的主键是10位字符型的,我想用函数生成一个自增主键,却不行

create table IntKey ( KeyValue Int);
insert into IntKey values(0);

--主键生成函数,主键10位字符
create function GetKey returns char(10)
as
begin
declare @KeyValue Int
update IntKey set @KeyValue = KeyValue = KeyValue + 1
return 'OP' + right('00000000' + convert(varchar(8),@KeyValue),8)
end

在SQL 2005内运行出错:
消息 443,级别 16,状态 15,过程 GetKey,第 7 行
在函数内的 'UPDATE' 中对带副作用的或依赖于时间的运算符的使用无效。
...全文
189 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
cloudburst 2006-04-04
  • 打赏
  • 举报
回复
都不是好办法,SQL Server真是个垃圾数据库

不过非常谢谢ping3000
ping3000 2006-04-04
  • 打赏
  • 举报
回复
也可以建个索引用,select top 1 KeyChar from IntKey order by KeyChar desc
cloudburst 2006-04-04
  • 打赏
  • 举报
回复
我知道了你的做法了。可是select max()效率较低;
更重要的是每个表都要单独处理了
ping3000 2006-04-04
  • 打赏
  • 举报
回复
可以这样用:
create table IntKey(KeyChar char(10),字段 nvarchar(20))
insert into IntKey(KeyChar,字段)
select dbo.GetKey(),'字段值'
这样KeyChar就是自增的了
cloudburst 2006-04-04
  • 打赏
  • 举报
回复
谢谢ping3000,可是这个函数怎么用啊?

我要的是在插入数据时,可以这样写代码:insert into ... select GetKey(),...
然后主键数值是自增的
ping3000 2006-04-04
  • 打赏
  • 举报
回复
可以这样:
create table IntKey(KeyChar char(10))
go
create function GetKey()
returns char(10)
as
begin
declare @KeyValue int
declare @KeyReturn varchar(20)
set @KeyValue = cast(isnull((select max(KeyChar) from IntKey),0) as int) + 1
set @KeyReturn = '000000000' + ltrim(str(@KeyValue))
return right(@KeyReturn,10)
end

go

declare @i int
set @i = 0
while @i < 100
begin
insert into IntKey(KeyChar)
select dbo.GetKey()
set @i = @i + 1
end
select * from IntKey
go
drop function GetKey
drop table IntKey
cloudburst 2006-04-04
  • 打赏
  • 举报
回复
用户定义函数不能用于执行一组修改全局数据库状态的操作,只能对函数内的临时表进行INSERT,DELETE和UPDATE操作

垃圾数据库,什么破规定啊
eddy8863 2006-04-03
  • 打赏
  • 举报
回复
可以用触发器的

22,301

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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