使用CASE语句从另一个表获取表名

时间:2019-06-22 20:03:26

标签: sql sql-server database azure

我需要根据ID列删除记录。我们已经使用外键在数据库中实现了引用完整性。标识了层次结构,并在外键表中指示了父表数据之前删除所有子表数据的顺序,如下所示:

id tablename
10 childtable1
 9 childtable2
 8 childtable3
 7 childtable4
 6 childtable5
 5 childtable6
 4 childtable7
 3 childtable8
 2 childtable9
 1 childtable10
 0 parenttable

删除数据的查询如下:

BEGIN TRANSACTION
DECLARE @i INT
SET @i=0

WHILE @@ROWCOUNT > 0            
DELETE TOP (100000) FROM mytable
WHERE NOT EXISTS
(SELECT 1 FROM dbo.myIDtable 
    WHERE myIDtable.ID = mytable.ID
        AND myIDtable.ID IN (1,2)
)
SET @i=@i+1
COMMIT;

问题是我需要根据上面列出的外键表ID列的值将表名传递给delete语句。

我该如何完成?

我们正在使用azure sql数据库,该数据库不允许跨数据库查询,而不会为每个涉及的表创建外部表。我们有150多个表,所以这不是一个选择。

BEGIN TRANSACTION
DECLARE @i INT
SET @i=0

WHILE @@ROWCOUNT > 0            
DELETE TOP (100000) FROM mytable
WHERE NOT EXISTS
(SELECT 1 FROM dbo.myIDtable 
    WHERE myIDtable.ID = mytable.ID
        AND myIDtable.ID IN (1,2)
) AND mytable = (select case id
when 10 then RTRIM(LTRIM(SUBSTRING(TABLENAME, 60, 50)))
when 9 then RTRIM(LTRIM(SUBSTRING(TABLENAME, 55, 50)))
when 8 then RTRIM(LTRIM(SUBSTRING(TABLENAME, 49, 50)))
when 7 then RTRIM(LTRIM(SUBSTRING(TABLENAME, 43, 50)))
when 6 then RTRIM(LTRIM(SUBSTRING(TABLENAME, 37, 50)))                          when 5 then RTRIM(LTRIM(SUBSTRING(TABLENAME, 31, 50)))
when 4 then RTRIM(LTRIM(SUBSTRING(TABLENAME, 25, 50)))
when 3 then RTRIM(LTRIM(SUBSTRING(TABLENAME, 19, 50)))
when 2 then RTRIM(LTRIM(SUBSTRING(TABLENAME, 13, 50)))
when 1 then RTRIM(LTRIM(SUBSTRING(TABLENAME, 7, 50)))
else tablename
end       
from dbo.foreignkeytable)
SET @i=@i+1
COMMIT;

0 个答案:

没有答案