Find string anywhere in Sql Database


/ Published in: SQL
Save to your folder(s)



Copy this code and paste it in your HTML
  1. CREATE PROC SearchAllTables
  2. (
  3. @SearchStr nvarchar(100)
  4. )
  5. AS
  6. BEGIN
  7.  
  8.  
  9. CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
  10.  
  11. SET NOCOUNT ON
  12.  
  13. DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
  14. SET @TableName = ''
  15. SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
  16.  
  17. WHILE @TableName IS NOT NULL
  18. BEGIN
  19. SET @ColumnName = ''
  20. SET @TableName =
  21. (
  22. SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
  23. FROM INFORMATION_SCHEMA.TABLES
  24. WHERE TABLE_TYPE = 'BASE TABLE'
  25. AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
  26. AND OBJECTPROPERTY(
  27. OBJECT_ID(
  28. QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
  29. ), 'IsMSShipped'
  30. ) = 0
  31. )
  32.  
  33. WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
  34. BEGIN
  35. SET @ColumnName =
  36. (
  37. SELECT MIN(QUOTENAME(COLUMN_NAME))
  38. FROM INFORMATION_SCHEMA.COLUMNS
  39. WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
  40. AND TABLE_NAME = PARSENAME(@TableName, 1)
  41. AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
  42. AND QUOTENAME(COLUMN_NAME) > @ColumnName
  43. )
  44.  
  45. IF @ColumnName IS NOT NULL
  46. BEGIN
  47. INSERT INTO #Results
  48. EXEC
  49. (
  50. 'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
  51. FROM ' + @TableName + ' (NOLOCK) ' +
  52. ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
  53. )
  54. END
  55. END
  56. END
  57.  
  58. SELECT ColumnName, ColumnValue FROM #Results
  59. END

URL: http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.