我有一个表有id和语句列,语句列包含类似insert into tablename,update tablename,delete tablename(tablename可能是任何xxx)的语句,我有一个场景,我需要编写一个存储过程,如果我运行SP它应首先在语句列中获取插入记录,首先使用父表名,然后将子表插入到语句中,插入后更新语句应以任何方式进行,最后使用子表语句首先删除语句,然后是父语句。
输出应该像
statements
INSERT INTO country(parent to state)
INSERT INTO state(parent to city)
INSERT INTO city(parent to zipcode)
INSERT INTO zipcode
答案 0 :(得分:0)
您好,为了完成您的程序,您必须再保留1个像seqno int这样的列,并使用父子级别更新seqno。从语句列中读取表名并从sql server中查找父子级是非常困难的 所以我假设你在那个表中有seqno,那么你可以按照以下方式编写proc
DECLARE @table table (statements varchar(200),id int,seqno int)
INSERT INTO @table
values('INSERT INTO country(parent to state)',1,1),
('INSERT INTO state(parent to city)',2,2),
('INSERT INTO city(parent to zipcode)' ,3,3),
('INSERT INTO zipcode' ,4,4),
('update city(parent to zipcode)' ,4,3),
('delete FROM country' ,7,1),
('delete FROM zipcode' ,6,4)
--- you can change below code to proc u can write case statements if u want only inset or delete like that
DECLARE @outtable table(statements varchar(200),seqno int,id int iDENTITY(1,1))
INSERT INTO @outtable
SELECT statements,seqno FROM @table WHERE statements like '%insert%' ORDER BY seqno ASC
INSERT INTO @outtable
SELECT statements,seqno FROM @table WHERE statements like '%update%' ORDER BY seqno ASC
INSERT INTO @outtable
SELECT statements,seqno FROM @table WHERE statements like '%delete%' ORDER BY seqno DESC
SELECT * FROM @outtable order by id asc