0

我有一个表,其中包含 id 和语句列,语句列包含诸如插入表名、更新表名、删除表名(表名可能是任何 xxx)之类的语句,如果我运行 SP,我有一个需要编写存储过程的场景它应该首先使用父表名获取语句列中的插入记录,然后是子表插入到语句中,插入后更新语句应该以任何方式出现,最后是删除语句,首先是子表语句,然后是父表。

输出应该像

statements
INSERT INTO country(parent to state)
INSERT INTO state(parent to city)
INSERT INTO city(parent to zipcode)
INSERT INTO zipcode
4

1 回答 1

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
于 2012-10-17T00:05:30.750 回答