如何批量生成插入语句?
有表有几百条数据,如:
id tid cid
1 001 001
2 002 005
3 004 010
。。。
想生成如下语句:
update lease set tid='001',cid='001' where leaseid='1'
update lease set tid='002',cid='005' where leaseid='2'
update lease set tid='004',cid='010' where leaseid='3'
。。。
请高手指点
我的思路是建个空表,插入语句,但不会用插入语句+select,不知有什么好办法。
insert into abc(a) values('update lease set tid=''select * from bbb'',cid=''001'' where id=''1''')???
[解决办法]
你想要的结果不需要生成插入语句,可以这样
生成批量更新语句
select 'update lease set tid='''+tid''',cid='''+cid+''' where leaseid='''+cast(id as varchar)+''''
from tb
如果要生成select 插入语句,那么格式
insert into abc(a)
select id
from tb
where (条件表达式)
[解决办法]
--关联修改
CREATE TABLE test1
(
id INT,
tid NVARCHAR(10),
cid NVARCHAR(10)
)
INSERT INTO test1
SELECT 1,'001','001' UNION ALL
SELECT 2,'002','005' UNION ALL
SELECT 3,'004','010'
UPDATE lease set tid=test1.tid,cid=test1.cid
FROM test1
where lease.leaseid=test1.id
if OBJECT_ID('tempdb..#temp', 'u') is not null drop table #temp;
go
create table #temp( [id] varchar(100), [tid] varchar(100), [cid] varchar(100));
insert #temp
select '1','001','001' union all
select '2','002','005' union all
select '3','004','010'
--SQL:
SELECT sqltext = 'update lease set tid='''+ tid +''',cid='''+ cid +''' where leaseid=''1'''
INTO #newtable
from #temp
SELECT * FROM #newtable
/*
sqltext
update lease set tid='001',cid='001' where leaseid='1'
update lease set tid='002',cid='005' where leaseid='1'
update lease set tid='004',cid='010' where leaseid='1'
*/
update a
set a.tid=b.tid,
a.cid=b.cid
from lease a
inner join [表名] b on a.leaseid=b.id