从所有表中删除ID记录

时间:2013-05-15 15:24:13

标签: sql tsql

我希望能够快速删除“主”表和所有关联表中与特定“主”记录相关的所有记录。这主要是为了让我可以轻松输入测试记录,然后删除它们的所有痕迹,这需要很长时间手动,因为有几十个表可以引用记录。

因此,总而言之,在任何包含名为AdmissionID的列的表中,我想删除AdmissionID等于我将指定的值的所有记录。我以为我可以很容易地做到这一点。这是我的存储过程:

ALTER PROCEDURE [Admin].[sp_RemoveByAdmissionID]

@admissionID int

AS
--Removes records from all tables relating the AdmissionID entered

DECLARE @loop INT
DECLARE @object sysname
DECLARE @cmdstring varchar(500)

IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL 
 BEGIN
  DROP TABLE #TEMP
 END

SELECT 
    TABLE_NAME
    ,ROW_NUMBER() OVER (ORDER BY TABLE_NAME) ROWID
INTO #TEMP
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'BASE TABLE'

WHILE @loop <= (SELECT MAX(ROWID) FROM #TEMP)
  BEGIN
    SELECT @object = TABLE_NAME FROM #TEMP WHERE ROWID = @loop
        IF EXISTS (SELECT * FROM SYS.COLUMNS WHERE Name = 'AdmissionID' AND Object_ID = Object_ID(@object))
        BEGIN
            SET @cmdstring = 'DELETE FROM ' + @object + ' WHERE AdmissionID = ' + @admissionID
            Exec(@cmdstring)
        END    
  SET @loop += 1
  END

不幸的是,执行此过程不会从任何地方删除任何记录。我怀疑问题可能与我的参数没有被包含在我构建cmdstring字符串的行中的引号中有关,但是即使尝试缓解这一点似乎也没有用。

关于我哪里出错的建议,或者有更简单的方法吗?我不想在我的PK-FK关系中使用级联删除。


更新 按照Luv的建议,我发现他的查询确实返回了一个非常好的列表,列出了我想要使用的确切命令。我认为那里很容易,但我仍然无法做到这一点。我正在尝试的新SP如下:

ALTER PROCEDURE TEST

@admissionID VARCHAR(10)

AS

DECLARE @loop INT
DECLARE @cmd VARCHAR(500)


IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL 
BEGIN
DROP TABLE #TEMP
END

SELECT 'DELETE FROM '+ C.TABLE_NAME +' WHERE AdmissionID = '+@admissionID AS cmd
,ROW_NUMBER() OVER (ORDER BY 'DELETE FROM '+ C.TABLE_NAME +' WHERE AdmissionID = '+@admissionID) ROWID
INTO #TEMP
FROM INFORMATION_SCHEMA.COLUMNS C
INNER JOIN INFORMATION_SCHEMA.TABLES T on C.TABLE_NAME=T.TABLE_NAME
WHERE C.COLUMN_NAME='AdmissionID'
AND T.TABLE_TYPE='BASE TABLE'

WHILE @loop <= (SELECT MAX(ROWID) FROM #TEMP)
    BEGIN
SELECT @cmd = cmd 
FROM #TEMP
WHERE ROWID = @loop

EXEC(@cmd)      
SET @loop += 1
END

1 个答案:

答案 0 :(得分:4)

复制 Below Query 的结果并运行查询。

declare @yourvalue varchar
set @yourvalue=''
select 'DELETE FROM '+ C.TABLE_NAME +' WHERE AdmissionID = '+@yourvalue 
from INFORMATION_SCHEMA.COLUMNS C
INNER JOIN INFORMATION_SCHEMA.TABLES T on C.TABLE_NAME=T.TABLE_NAME
where C.COLUMN_NAME='AdmissionID'
and T.TABLE_TYPE='BASE TABLE'

您甚至可以制作 SP execute Dynamically