【发布时间】:2010-08-24 04:42:29
【问题描述】:
我需要获取存储过程(不是标准的,只有自定义的)来删除未使用的行表(table1)和其他一些表(table2、table3、table4...- 我们不知道有多少表引用通过 FOREIGN KEY CONSTRAINT 到 table1) 可以引用这个表。
例如:
СREATE PROCEDURE [dbo].[delete_on_constraints]
@table varchar(36) – table name we need to delete unused rows
@column varchar(36) – column name - primary key, on which other tables refers by FOREIGN KEY CONSTRAINT
有table1和table2,table3引用table1(提醒,我们不知道有多少表通过FOREIGN KEY CONSTRAINT引用table1)
CREATE TABLE [table1] (
[id] [int] IDENTITY (1, 1) NOT NULL CONSTRAINT [PK_ table1] PRIMARY KEY,
[value] [int] NULL
)
GO
CREATE TABLE [table2] (
[id] [int] IDENTITY (1, 1) NOT NULL CONSTRAINT [PK_ table2] PRIMARY KEY,
[table1_id] [int] NOT NULL ,
CONSTRAINT [FK_ table2_ table1] FOREIGN KEY ([table1_id]) REFERENCES [table1] ( [id] )
)
GO
CREATE TABLE [table3] (
[id] [int] IDENTITY (1, 1) NOT NULL CONSTRAINT [PK_ table3] PRIMARY KEY,
[table1_id] [int] NOT NULL ,
CONSTRAINT [FK_ table3_ table1] FOREIGN KEY ([table1_id]) REFERENCES [table1] ( [id] )
)
GO
INSERT INTO [table1] VALUES (100)
INSERT INTO [table1] VALUES (200)
INSERT INTO [table1] VALUES (300)
INSERT INTO [table1] VALUES (400)
GO
INSERT INTO [table2] VALUES (1)
INSERT INTO [table2] VALUES (3)
GO
INSERT INTO [table3] VALUES (1)
INSERT INTO [table3] VALUES (2)
INSERT INTO [table3] VALUES (3)
表中有行在调用存储过程
table1
id value
1 100
2 200
3 300
4 400
table2
id table1_id
1 1
2 3
table3
id table1_id
1 1
2 2
3 3
之后 [dbo].[delete_on_constraints] 'table1' 'id' 过程调用
table1
id value
1 100
2 200
3 300
【问题讨论】:
标签: sql-server tsql