sqlserver中在指定数据库的所有表的所有列中搜索给定的值
前端之家收集整理的这篇文章主要介绍了
sqlserver中在指定数据库的所有表的所有列中搜索给定的值,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
比如:我们导入了某个客户的资料,我们知道此客户的姓名是ZhangShan,我们想知道,在我们的业务数据库(eg:NorthWind)中,有哪些数据表的哪些字段设置了此姓名值ZhangShan,通过下面的sql,我们就可以实现此目的,此处的sql搜索自网上,在此处做了局部修改。
一、搜索数据是String类型
适用于搜索Text,NText,Varchar,Nvarchar,Char,NChar等类型
1、创建存储过程:My_Search_StringInGivenTable
<div class="codetitle"><a style="CURSOR: pointer" data="51337" class="copybut" id="copybut51337" onclick="doCopy('code51337')"> 代码如下:
<div class="codebody" id="code51337">
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','')
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('')),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_Execute
sql @
sql,N'@SearchString nvarchar(max)',@SearchString
END