表a,有很多很多字段,其中ID为主键,ret为查询条件.
我要做的是根据传来的ret,在表a中查出这条数据,然后再重新插入表a,同时,改变ID的值(因为是主键).
如果没有主键,可以直接写insert into a select * from a where ret='' 可是现在有个主键,怎么办啊?字段非常的多,不可能一个一个写出来insert into values(a,b,c,d,e...)像这样不行的.,..大家帮帮忙..
我要做的是根据传来的ret,在表a中查出这条数据,然后再重新插入表a,同时,改变ID的值(因为是主键).
如果没有主键,可以直接写insert into a select * from a where ret='' 可是现在有个主键,怎么办啊?字段非常的多,不可能一个一个写出来insert into values(a,b,c,d,e...)像这样不行的.,..大家帮帮忙..
declare @s varchar(2000)
set @s = ''
select @s = @s + stuff(
(select ','+[name] from syscolumns
where id = object_id('tb') and [name]!='field1' for xml path('')),1,1,'')
--print @s
exec ('select '+@s +' from tb')表tb
去掉字段field1
declare @col nvarchar(2000)
select @col=isnull(@col,'')+','+b.name from sys.sysobjects a join sys.syscolumns b on a.id=b.id
where a.name='sysrowsets'
select stuff(@col,1,1,'')
--rowsetid,ownertype,idmajor,idminor,numpart,status,fgidfs,rcrows
select @str=stuff((select ','+name from syscolumns where id=object_id('a') and name<>'id' for xml path('')),1,1,'')
exec('insert into a('+@str+') select '+@str+' from a where ret=''''')
例如表a,3个字段,ID,name,age,其中id为主键
insert into a select * from a where name=''
这样插入肯定提示id不能插入重复列,我的意思是,怎么在插入的同时,改变id的值
insert into a select name,age from a where name=''这个...我压力很大...
不管你有多少
declare @s varchar(2000)
set @s = ''
select @s = @s + stuff(
(select ','+[name] from syscolumns
where id = object_id('a') and [name]!='id' for xml path('')),1,1,'')
--print @s
exec ('select '+@s +' from a')---可以先通过这个看效果。
都能查出来,tb换成你的表名称 field1换成id(也就是你要排查的列)id是不是自增的?自增的就不用指定了exec('insert into a select '+@s +' from a where ret =''条件值''')