程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> 其他數據庫知識 >> 更多數據庫知識 >> sqlserver中在指定數據庫的所有表的所有列中搜索給定的值

sqlserver中在指定數據庫的所有表的所有列中搜索給定的值

編輯:更多數據庫知識

比如:我們導入了某個客戶的資料,我們知道此客戶的姓名是ZhangShan,我們想知道,在我們的業務數據庫(eg:NorthWind)中,有哪些數據表的哪些字段設置了此姓名值ZhangShan,通過下面的SQL,我們就可以實現此目的,此處的SQL搜索自網上,在此處做了局部修改。
一、搜索數據是String類型
適用於搜索Text,NText,Varchar,Nvarchar,Char,NChar等類型
1、創建存儲過程:My_Search_StringInGivenTable
復制代碼 代碼如下:
USE [NORTHWIND]
GO
/****** Object: StoredProcedure [dbo].[My_Search_StringInGivenTable] Script Date: 09/25/2011 15:37:14 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[My_Search_StringInGivenTable]
(@SearchString NVARCHAR(MAX),
@Table_Schema sysname,
@Table_Name sysname)
AS
BEGIN
DECLARE @Columns NVARCHAR(MAX), @Cols NVARCHAR(MAX), @PkColumn NVARCHAR(MAX)
-- Get all character columns
SET @Columns = STUFF((SELECT ', ' + QUOTENAME(Column_Name)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE IN ('text','ntext','varchar','nvarchar','char','nchar')
AND TABLE_NAME = @Table_Name
ORDER BY COLUMN_NAME
FOR XML PATH('')),1,2,'')
IF @Columns IS NULL -- no character columns
RETURN -1
-- Get columns for select statement - we need to convert all columns to nvarchar(max)
SET @Cols = STUFF((SELECT ', cast(' + QUOTENAME(Column_Name) + ' as nvarchar(max)) as ' + QUOTENAME(Column_Name)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE IN ('text','ntext','varchar','nvarchar','char','nchar')
AND TABLE_NAME = @Table_Name
ORDER BY COLUMN_NAME
FOR XML PATH('')),1,2,'')
SET @PkColumn = STUFF((SELECT N' + ''|'' + ' + ' cast(' + QUOTENAME(CU.COLUMN_NAME) + ' as nvarchar(max))'
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CU ON TC.TABLE_NAME = CU.TABLE_NAME
AND TC.TABLE_SCHEMA = CU.TABLE_SCHEMA
AND Tc.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
WHERE TC.CONSTRAINT_TYPE ='PRIMARY KEY' AND TC.TABLE_SCHEMA = @Table_Schema AND TC.TABLE_NAME = @Table_Name
ORDER BY CU.COLUMN_NAME
FOR XML PATH('')),1,9,'')
IF @PkColumn IS NULL
SELECT @PkColumn = 'cast(NULL as nvarchar(max))'
-- set select statement using dynamic UNPIVOT
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = 'select *, ' + QUOTENAME(@Table_Schema,'''') + 'as [Table Schema], ' + QUOTENAME(@Table_Name,'''') + ' as [Table Name]' +
' from
(select '+ @PkColumn + ' as [PK Column], ' + @Cols + ' from ' + QUOTENAME(@Table_Name) +
' )src UNPIVOT ([Column Value] for [Column Name] IN (' + @Columns + ')) unpvt
WHERE [Column Value] LIKE ''%'' + @SearchString + ''%'''
--print @SQL
EXECUTE sp_ExecuteSQL @SQL, N'@SearchString nvarchar(max)', @SearchString
END

2、創建搜索存儲過程:My_Search_String_AllTables
此存儲過程將遍歷指定數據庫的所有表,並利用上面創建的存儲過程My_Search_StringInGivenTable來取得每個表的搜索結果。
復制代碼 代碼如下:
USE [NORTHWIND]
GO
/****** Object: StoredProcedure [dbo].[My_Search_String_AllTables] Script Date: 09/25/2011 15:41:58 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROC [dbo].[My_Search_String_AllTables]
(
@SearchString NVARCHAR(MAX)
)
AS
BEGIN
CREATE TABLE #RESULT ([PK COLUMN] NVARCHAR(MAX), [COLUMN VALUE] NVARCHAR(MAX), [COLUMN Name] sysname,
[TABLE SCHEMA] sysname, [TABLE Name] sysname)
DECLARE @Table_Name sysname, @Table_Schema sysname
DECLARE curAllTables CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY
FOR
SELECT Table_Schema, Table_Name
FROM INFORMATION_SCHEMA.Tables
WHERE TABLE_TYPE = 'BASE TABLE'
ORDER BY Table_Schema, Table_Name
OPEN curAllTables
FETCH curAllTables
INTO @Table_Schema, @Table_Name
WHILE (@@FETCH_STATUS = 0) -- Loop through all tables in the database
BEGIN
INSERT #RESULT
EXECUTE My_Search_StringInGivenTable @SearchString, @Table_Schema, @Table_Name
FETCH curAllTables
INTO @Table_Schema, @Table_Name
END -- while
CLOSE curAllTables
DEALLOCATE curAllTables
-- Return results
SELECT * FROM #RESULT ORDER BY [Table Name]
END

使用示例
復制代碼 代碼如下:
USE [NORTHWIND]
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[My_Search_String_AllTables]
@SearchString = N'WantValue'
SELECT 'Return Value' = @return_value
GO

還有另一個版本,就是直接創建一個存儲過程來取得所要結果,但個人覺得前面那個方法更具靈活性
復制代碼 代碼如下:
USE [NORTHWIND]
GO
/****** Object: StoredProcedure [dbo].[ZL_SearchAllTables] Script Date: 09/25/2011 15:44:10 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROC [dbo].[ZL_SearchAllTables]
(
@SearchStr nvarchar(100)
)
AS
BEGIN
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END
[code]
二、搜索數據是Int類型
適用於搜索smallint, tinyint, int, bigint等類型
1、創建存儲過程 My_Search_IntInGivenTable
[code]
USE [NORTHWIND]
GO
/****** Object: StoredProcedure [dbo].[My_Search_IntInGivenTable] Script Date: 09/25/2011 15:45:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[My_Search_IntInGivenTable]
(@SearchValue INT,
@Table_Schema sysname,
@Table_Name sysname)
AS
BEGIN
DECLARE @Columns NVARCHAR(MAX) ,
@Cols NVARCHAR(MAX) ,
@PkColumn NVARCHAR(MAX) ,
@SQL NVARCHAR(MAX)
--判斷並創建#Result表
IF OBJECT_ID('TempDB..#Result', 'U') IS NOT NULL
DROP TABLE #Result
CREATE TABLE #RESULT
(
[PK COLUMN] NVARCHAR(MAX) ,
[COLUMN VALUE] BIGINT ,
[COLUMN Name] SYSNAME ,
[TABLE SCHEMA] SYSNAME ,
[TABLE Name] SYSNAME
)
--開始搜索給定的表
DECLARE curAllTables CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY
FOR
SELECT Table_Schema ,
Table_Name
FROM INFORMATION_SCHEMA.Tables
WHERE Table_Name =@Table_Name
OPEN curAllTables
WHILE 1 = 1
BEGIN
FETCH curAllTables
INTO @Table_Schema, @Table_Name
IF @@FETCH_STATUS <> 0 -- Loop through all tables in the database
BREAK
PRINT CHAR(13) + 'Processing ' + QUOTENAME(@Table_Schema) + '.'
+ QUOTENAME(@Table_Name)
-- Get all int columns
SET @Columns = STUFF(( SELECT ', ' + QUOTENAME(Column_Name)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE LIKE '%int'
AND TABLE_NAME = @Table_Name
AND table_schema = @Table_Schema
ORDER BY COLUMN_NAME
FOR
XML PATH('')
), 1, 2, '')
IF @Columns IS NULL
BEGIN
PRINT 'No int columns in the ' + QUOTENAME(@Table_Schema)
+ '.' + QUOTENAME(@Table_Name)
CONTINUE
END
-- Get columns for select statement - we need to convert all columns to bigint
SET @Cols = STUFF(( SELECT ', cast(' + QUOTENAME(Column_Name)
+ ' as bigint) as '
+ QUOTENAME(Column_Name)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE LIKE '%int'
AND TABLE_NAME = @Table_Name
ORDER BY COLUMN_NAME
FOR
XML PATH('')
), 1, 2, '')
-- Create PK column(s)
SET @PkColumn = STUFF(( SELECT N' + ''|'' + ' + ' cast('
+ QUOTENAME(CU.COLUMN_NAME)
+ ' as nvarchar(max))'
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE CU ON TC.TABLE_NAME = CU.TABLE_NAME
AND TC.TABLE_SCHEMA = CU.TABLE_SCHEMA
AND Tc.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
WHERE TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TC.TABLE_SCHEMA = @Table_Schema
AND TC.TABLE_NAME = @Table_Name
ORDER BY CU.COLUMN_NAME
FOR
XML PATH('')
), 1, 9, '')
IF @PkColumn IS NULL
SELECT @PkColumn = 'cast(NULL as nvarchar(max))'
-- set select statement using dynamic UNPIVOT
SET @SQL = 'select *, ' + QUOTENAME(@Table_Schema, '''')
+ 'as [Table Schema], ' + QUOTENAME(@Table_Name, '''')
+ ' as [Table Name]' + ' from
(select ' + @PkColumn + ' as [PK Column], ' + @Cols + ' from '
+ QUOTENAME(@Table_Schema) + '.' + QUOTENAME(@Table_Name)
+ ' )src UNPIVOT ([Column Value] for [Column Name] IN ('
+ @Columns + ')) unpvt
WHERE [Column Value] = @SearchValue'
--print @SQL -- if we get errors, we may want to print generated SQL
INSERT #RESULT
( [PK COLUMN] ,
[COLUMN VALUE] ,
[COLUMN Name] ,
[TABLE SCHEMA] ,
[TABLE Name]
)
EXECUTE sp_ExecuteSQL @SQL, N'@SearchValue int', @SearchValue
PRINT 'Found ' + CAST(@@ROWCOUNT AS VARCHAR(10)) + ' records in '
+ QUOTENAME(@Table_Schema) + '.' + QUOTENAME(@Table_Name)
END
CLOSE curAllTables
DEALLOCATE curAllTables
SELECT *
FROM #RESULT
ORDER BY [TABLE SCHEMA] ,
[TABLE Name]
END

2、創建搜索存儲過程My_Search_Int_AllTables,與上面類似,此存儲過程將調用 My_Search_IntInGivenTable來實現所遍歷的每一個數據表的搜索結果
復制代碼 代碼如下:
USE [NORTHWIND]
GO
/****** Object: StoredProcedure [dbo].[My_Search_Int_AllTables] Script Date: 09/25/2011 15:48:29 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROC [dbo].[My_Search_Int_AllTables]
(
@SearchValue INT
)
AS
BEGIN
CREATE TABLE #RESULT ([PK COLUMN] NVARCHAR(MAX), [COLUMN VALUE] NVARCHAR(MAX), [COLUMN Name] sysname,
[TABLE SCHEMA] sysname, [TABLE Name] sysname)
DECLARE @Table_Name sysname, @Table_Schema sysname
DECLARE curAllTables CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY
FOR
SELECT Table_Schema, Table_Name
FROM INFORMATION_SCHEMA.Tables
WHERE TABLE_TYPE = 'BASE TABLE'
ORDER BY Table_Schema, Table_Name
OPEN curAllTables
FETCH curAllTables
INTO @Table_Schema, @Table_Name
WHILE (@@FETCH_STATUS = 0) -- Loop through all tables in the database
BEGIN
INSERT #RESULT
EXECUTE My_Search_StringInGivenTable @SearchValue, @Table_Schema, @Table_Name
FETCH curAllTables
INTO @Table_Schema, @Table_Name
END -- while
CLOSE curAllTables
DEALLOCATE curAllTables
-- Return results
SELECT * FROM #RESULT ORDER BY [Table Name]
END

使用示例
復制代碼 代碼如下:
USE [NORTHWIND]
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[My_Search_Int_AllTables]
@SearchValue = 68
SELECT 'Return Value' = @return_value
GO

Note:
1、你可以根據上面一、二中的第1個存儲過程來實現只搜索指定某些數據表的功能。
2、對於其它數據類型如:Date,Real等等均可以此為參照進行修改。
3、此方法對大型數據庫會很耗時,所以盡量在小數據庫上調試。當需要在大數據庫上操作時,盡量避開數據庫使用高峰時段並要有耐心。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved