在資料庫中查詢關鍵字

xiangchengboy發表於2011-01-20

--建立儲存過程:sp_ValueSearch

CREATE PROC sp_ValueSearch
@value sql_variant, --要搜尋的資料
@precision bit=1 --1=僅根據sql_variant中的資料型別查詢對應型別的資料列.<>1,查詢相容的所有列,字元資料使用like匹配
AS
SET NOCOUNT ON
IF @value IS NULL RETURN

--資料型別處理
SELECT xtype INTO #t FROM systypes
WHERE name=SQL_VARIANT_PROPERTY(@value,N'BaseType')

--擴充套件資料型別及查詢處理語句
DECLARE @sql nvarchar(4000),@sql1 nvarchar(4000)
IF @precision=1
  SET @sql=CASE SQL_VARIANT_PROPERTY(@value,N'BaseType')
  WHEN N'text' THEN N' LIKE N''%''+CAST(@value as varchar(8000))+''%'''
  WHEN N'ntext' THEN N' LIKE ''%''+CAST(@value as nvarchar(4000))+''%'''
  ELSE N'=@value' END
ELSE
BEGIN
  SET @sql=CAST(SQL_VARIANT_PROPERTY(@value,N'BaseType') as sysname)
  IF @sql LIKE N'%char' or @sql LIKE N'%text'
  BEGIN
  INSERT #t SELECT xtype FROM systypes
  WHERE name LIKE N'%char' or name LIKE N'%text'
  SELECT @sql=N' LIKE N''%''+CAST(@value as '
  +CASE 
  WHEN LEFT(@sql,1)=N'n' THEN ' nvarchar(4000)'
  ELSE 'varchar(8000)' END
  +N')+N''%'''
  END
  ELSE IF @sql LIKE N'%datetime'
  BEGIN
  INSERT #t SELECT xtype FROM systypes
  WHERE name LIKE N'%datetime'
  SET @sql=N'=@value'  
  END
  ELSE IF @sql LIKE N'%int' 
  OR @sql LIKE N'%money' 
  OR @sql IN(N'real',N'float',N'decimal',N'numeric')
  BEGIN
  INSERT #t SELECT xtype FROM systypes
  WHERE name LIKE N'%int' 
  OR name LIKE N'%money' 
  OR name IN(N'real',N'float',N'decimal')
  SET @sql=N'=@value'  
  END
  ELSE
  SET @sql=N'=@value'
END
--儲存結果的臨時表
CREATE TABLE #(TableName sysname,FieldName sysname,Type sysname,SQL nvarchar(4000))

DECLARE tb CURSOR LOCAL
FOR
SELECT N'SELECT * FROM '
  +QUOTENAME(USER_NAME(o.uid))
  +N'.'+QUOTENAME(o.name)
  +N' WHERE '+QUOTENAME(c.name)
  +@sql,
  N'INSERT # VALUES(N'+QUOTENAME(o.name,N'''')
  +N',N'+QUOTENAME(c.name,N'''')
  +N',N'+QUOTENAME(QUOTENAME(t.name)+CASE 
  WHEN t.name IN (N'decimal',N'numeric')
  THEN N'('+CAST(c.prec as varchar)+N','+CAST(c.scale as varchar)+N')'
  WHEN t.name=N'float'
  OR t.name like N'%char'
  OR t.name like N'%binary'
  THEN N'('+CAST(c.prec as varchar)+N')'
  ELSE N'' END,N'''')
  +N',@sql)'
FROM sysobjects o,syscolumns c,systypes t,#t tt
WHERE o.id=c.id
  AND c.xusertype=t.xusertype
  AND t.xtype=tt.xtype
  AND OBJECTPROPERTY(o.id,N'IsUserTable')=1

OPEN tb
FETCH tb INTO @sql,@sql1
WHILE @@FETCH_STATUS=0
BEGIN
  SET @sql1=N'IF EXISTS('+@sql+N') '+@sql1
  EXEC sp_executesql @sql1,N'@value sql_variant,@sql nvarchar(4000)',@value,@sql
  FETCH tb INTO @sql,@sql1
END
CLOSE tb
DEALLOCATE tb
SELECT * FROM #

 

--執行儲存過程查詢:

exec sp_ValueSearch '要搜尋的值',1 --1或不輸入(即預設值1)精確匹配
exec sp_ValueSearch '要搜尋的值',0 --不等於1,模糊匹配

--注:在查詢數字型欄位時要把搜尋值的引號去掉,比如,exec sp_ValueSearch 100,1

相關文章