读书人

SQL插入记录时怎么使其中一列值与

发布时间: 2012-10-20 14:12:48 作者: rapoo

请教高手,SQL插入记录时,如何使其中一列值与自动增长的例值相同啊
如题,
如例
AutoNum Same
1 1
2 2
3 3
4 4
5 5
6 6

autoNum 是自动增长字段
same字段,不能为空 每次插入记录时 same 字段值总是与AutoNum相同,看到别人表是这样,但我怎么也插不进去记录,因为same 字段不能为空 又不知道怎么取autonum的值,请高手指点。。

[解决办法]
计算列。
sname as autonum
[解决办法]

SQL code
create table #tb(AutoNum int identity,Same int)insert #tb (Same)select 1declare @a intset @a=1while @a<=10begininsert #tbselect @@identity+1set @a=@a+1endselect * from #tb/*AutoNum    Same1    12    23    34    45    56    67    78    89    910    1011    11*/
[解决办法]
SQL code
create table #ttt(AutoNum int identity,Same as AutoNum,value char(1))insert #ttt(value)select 'a' union allselect 'b' union allselect 'c' union allselect 'd' union allselect 'e' union allselect 'f'select * from #ttt/*AutoNum    Same    value1    1    a2    2    b3    3    c4    4    d5    5    e6    6    f*/--如果还有别的字段
[解决办法]
insert info(name,sex)
select '张三','男' union all
select '李四',‘女’
[解决办法]
探讨

谢谢两位,不过我没有调明白,具体的insert语名怎么写啊
比如表 info
AutoNum Same name sex
1 1 张三 男
2 2 李四 女

insert info(name,sex,same) values ('张三','男','same 字段值怎么写啊')

[解决办法]
那你插入过后再更新一下表
update tbl set same=id
[解决办法]
alter table #ttt
drop column same
go
alter table #ttt
add same as AutoNum
go


改一下表结构吧
[解决办法]
SQL code
Create Trigger UpdateSname     On info After Update     AsUpdate info   Set same=id  FROM info a,inserted b WHERE a.AutoNum = b.AutoNum 

读书人网 >SQL Server

热点推荐