• MSSQL 查询某个值在哪个表哪个字段 及 实用SQL 锦集 同事分享的.感谢


    查数据库是否存在:select * From master.dbo.sysdatabases where name='test2'
    跨数据库查询: select * 
    from OPENDATASOURCE('SQLOLEDB','server=192.168.2.251;
    uid=sa;pwd=hzya924;database=Hayz_JJ_ERP').Hayz_JJ_ERP.dbo.T_Equipment
    查看表列名及说明:select   a.name   列名,isnull(cast(c.value   as   varchar(8000)), ' ')   描述   from   syscolumns   a   
    left   join   sysproperties   c   on   a.id   =   c.id   and 
      a.colid=c.smallid   where   a.id=object_id( 'System_Table ') 
    查看触发器是否存在:select * from sysobjects where id=object_id(N'trutest_id_delete') and objectproperty(id,N'IsTrigger')=1
    
    模糊查询整个数据库中的关键字:
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Full_Search]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
    drop procedure [dbo].[Full_Search]
    GO
    SET QUOTED_IDENTIFIER ON 
    GO
    SET ANSI_NULLS ON 
    GO
    CREATE proc Full_Search(@string varchar(50)) 
    as 
    begin 
    declare @t table  (
    所在表 varchar(50),
    所在列 varchar(50),
    辅助查询语句 nvarchar(1000)
    )
    declare @tbname varchar(50)  
    declare tbroy cursor  for select name from sysobjects   
    where xtype='u'   --第一个游标遍历所有的表 
      
    open tbroy 
    fetch next from tbroy into @tbname 
    while @@fetch_status=0 
    begin 
        
      declare @colname varchar(50) 
      declare colroy cursor for select a.name 
      from syscolumns  a inner join systypes b on a.xtype=b.xtype 
      where a.id=object_id(@tbname) and b.name in ('varchar','nvarchar','char','nchar')
       
    --数据类型为字符型的字段 
      open colroy 
      fetch next from colroy into @colname 
      while @@fetch_status=0 
      begin 
       
      declare @sql nvarchar(1000),@i int
      set @sql='select @i=count(1) from '+@tbname+' where '+@colname+' like ''%'+@string+'%''' 
      exec sp_executesql @sql,N'@i int output',@i output   --输出满足条件表的记录数 
    if @i>0 
    begin
    set @sql='select * from '+@tbname+' where '+@colname+' like ''%'+@string+'%'''
    insert into @t values(@tbname,@colname,@sql)
    end
      
      fetch next from colroy into @colname 
      end        
       
      close colroy 
      deallocate colroy 
      
    fetch next from tbroy into @tbname 
    end 
    close tbroy 
    deallocate tbroy 
    if not exists(select 1 from @t)
    print '字符串 "'+@string +'" 在当前数据库里不存在!'
    else
    select * from @t
    end 
    GO
    SET QUOTED_IDENTIFIER OFF 
    GO
    SET ANSI_NULLS ON 
    GO
    EXEC Full_Search '22' -- 22 即为要查找的字段值
  • 相关阅读:
    最少代码的瀑布流实现
    GoLang代码规范
    wcf基础知识之ListenUri和ListenUriMode实现 逻辑地址和物理地址的分离
    STL学习笔记 string
    Bitbucket上使用SSH协作
    使用注册表文件(REG)添加、 修改或删除注册表子项和值
    《大话设计模式》Python版代码实现
    go windows 32位环境搭建
    借书场景领域建模分析
    E/R模型学习
  • 原文地址:https://www.cnblogs.com/wuyifu/p/3120310.html
Copyright © 2020-2023  润新知