背景:
数据库StudentDB中,字段StudentNo存在多个表中,但是由于非正常操作导致插入一批非法的卡号信息到数据库中(正确的卡号由6位数字构成)。现需将这批非法卡号的相关信息删除。
解决方案:
USE [StudentDB]
GO
DECLARE @TableName varchar(100)
--申明一个表名游标
DECLARE Table_cursor CURSOR FOR
select name from sysobjects
where xtype= 'u'
--打开游标
OPEN Table_cursor
--取出值
FETCH NEXT FROM Table_cursor INTO @TableName
--循环取出游标的值
WHILE @@FETCH_STATUS = 0
BEGIN
if ( exists ( select * from dbo.syscolumns where (name = 'StudentNo') and id in
(select id from dbo.sysobjects where id = object_id(@TableName) and OBJECTPROPERTY(id, N'IsUserTable') = 1))
)
begin
declare @strsqlCard_no nchar(1000)
set @strsqlStudentNo = ' Delete from ' + @TableName + ' where ISNUMERIC(StudentNo) = 0 ';
exec sp_executesql @strsqlStudentNo
end
FETCH NEXT FROM Table_cursor
INTO @TableName
END
--关闭游标
CLOSE Table_cursor
--释放游标
DEALLOCATE Table_cursor