如何在一个SQL数据库中搜索到特定值的记录
只知道一个SQL数据库中某个表中某记录的某字段的值为“abcd”,但不知道具体在哪个表、哪个字段(即不知道字段名),表很多,如何知道哪此表和哪此记录、哪此字段值为特定的值...
只知道一个SQL数据库中某个表中某记录的某字段的值为“abcd”,但不知道具体在哪个表、哪个字段(即不知道字段名),表很多,如何知道哪此表和哪此记录、哪此字段值为特定的值
展开
1个回答
2013-07-11
展开全部
这样的话,给你一个思路,你先根据这个库,查找里面所有表名,然后再根据表名,查找字段名,然后再查找所有不是数字或者是二进制的字段进行搜索,当然这个需要多次循环,多次调用,肯定是很麻烦的!肯定得使用游标,虽然效率低,但是这个是唯一的一个办法:declare @tabName VARCHAR(40) declare @colName VARCHAR(40)DECLARE @sql nVARCHAR(2000)
set @sql = '';
DECLARE tabCursor CURSOR FOR sELECT name From sysobjects WHERE xtype = 'u' --查找库中所有的表OPEN tabCursorFETCH NEXT FROM tabCursor INTO @tabName
WHILE @@fetch_status = 0
BEGIN
-- SET @sql = 'UPDATE ' + @tabName + ' SET '
DECLARE colCursor CURSOR FOR Select Name FROM SysColumns Where id=Object_Id(@tabName) --查找表中所有的字段
OPEN colCursor
FETCH NEXT FROM colCursor INTO @colName
set @sql = ' select 1 from '+@tabName+ ' where '+ @colName +' like ''%10%'' '
WHILE @@fetch_status = 0
BEGIN
-- SET @sql = @sql + @colName + '=REPLACE(' +@colName+ ',''XX'',''''),'
set @sql += CHAR(10)+CHAR(13)+ ' select 1 from '+@tabName+ ' where '+ @colName +' like ''%10%'' '
FETCH NEXT FROM colCursor INTO @colName
END
-- SET @sql = LEFT(@sql,LEN(@sql)-1)
-- print @sql
EXEC(@sql)
CLOSE colCursor
DEALLOCATE colCursor
FETCH NEXT FROM tabCursor INTO @tabName
ENDCLOSE tabCursorDEALLOCATE tabCursor 此方法经过验证,但是需要你进行简单的修改!
set @sql = '';
DECLARE tabCursor CURSOR FOR sELECT name From sysobjects WHERE xtype = 'u' --查找库中所有的表OPEN tabCursorFETCH NEXT FROM tabCursor INTO @tabName
WHILE @@fetch_status = 0
BEGIN
-- SET @sql = 'UPDATE ' + @tabName + ' SET '
DECLARE colCursor CURSOR FOR Select Name FROM SysColumns Where id=Object_Id(@tabName) --查找表中所有的字段
OPEN colCursor
FETCH NEXT FROM colCursor INTO @colName
set @sql = ' select 1 from '+@tabName+ ' where '+ @colName +' like ''%10%'' '
WHILE @@fetch_status = 0
BEGIN
-- SET @sql = @sql + @colName + '=REPLACE(' +@colName+ ',''XX'',''''),'
set @sql += CHAR(10)+CHAR(13)+ ' select 1 from '+@tabName+ ' where '+ @colName +' like ''%10%'' '
FETCH NEXT FROM colCursor INTO @colName
END
-- SET @sql = LEFT(@sql,LEN(@sql)-1)
-- print @sql
EXEC(@sql)
CLOSE colCursor
DEALLOCATE colCursor
FETCH NEXT FROM tabCursor INTO @tabName
ENDCLOSE tabCursorDEALLOCATE tabCursor 此方法经过验证,但是需要你进行简单的修改!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询