作項目中前些天要手動改數據庫中的一些字段的值,但發現這個字段可能會被數據庫中其餘的不少張表引用,因而就得想辦法查詢出該條記錄的全部引用的表和字段,下面的存儲過程能夠查詢出整個數據庫中某個特定值所在的表和字段。sql
CREATE PROCEDURE [dbo].[SP_FindValueInDB] ( @value VARCHAR(1024) ) AS BEGIN SET NOCOUNT ON; DECLARE @sql VARCHAR(1024) DECLARE @table VARCHAR(64) DECLARE @column VARCHAR(64) CREATE TABLE #t ( tablename VARCHAR(64), columnname VARCHAR(64) ) DECLARE TABLES CURSOR FOR SELECT o.name, c.name FROM syscolumns c INNER JOIN sysobjects o ON c.id = o.id WHERE o.type = 'U' AND c.xtype IN (167, 175, 231, 239) ORDER BY o.name, c.name OPEN TABLES FETCH NEXT FROM TABLES INTO @table, @column WHILE @@FETCH_STATUS = 0 BEGIN SET @sql = 'IF EXISTS(SELECT NULL FROM [' + @table + '] ' SET @sql = @sql + 'WHERE RTRIM(LTRIM([' + @column + '])) LIKE ''%' + @value + '%'') ' SET @sql = @sql + 'INSERT INTO #t VALUES (''' + @table + ''', ''' SET @sql = @sql + @column + ''')' EXEC(@sql) FETCH NEXT FROM TABLES INTO @table, @column END CLOSE TABLES DEALLOCATE TABLES SELECT * FROM #t DROP TABLE #t End
只須要傳入一個想要查找的值,便可查詢出這個值所在的表和字段名。數據庫
EXEC [SP_FindValueInDB] 'GetAllCar'
查詢出來的結果以下:spa
轉自:https://blog.csdn.net/zengcong2013/article/details/55264202.net