循环通过一组表

时间:2015-07-22 09:45:53

标签: sql sql-server

我想找出SQL Server中在某些表中查找某些字符的最佳方法。 你能告诉我哪个是循环通过一组表/列的最好的方法,只使用SQL命令(存储过程......)找到一些字符?

提前致谢。

示例:

  1. 选择表/列组:
  2. SELECT t.name AS table_name
    , c.name AS column_name
    --, ty.Name
    FROM sys.tables AS t
    INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
    INNER JOIN sys.types ty ON c.user_type_id = ty.user_type_id
    where ty.Name = 'uniqueidentifier'
    
    1. 选择
    2. 的输出
       table_name                 column_name
       formset_details_translation    formset_details_translation_id
       formset_details_translation    formset_version_id
       current_schema_instances       original_unique_guid
      
      ...
      
      1. 寻找循环。我该怎么用?光标?
      2. for each Table
            For each Column
                select * 
                from tableI
                where columnI = 'XXXX...XXXX'
            End For
        End For
        

2 个答案:

答案 0 :(得分:2)

你正在看什么?

DECLARE @cnt INT,@ID int = 1
Declare @TempTable table(ID int IDENTITY(1,1), table_name varchar(200), column_name varchar(200))

Insert into @TempTable
SELECT t.name AS table_name
, c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
INNER JOIN sys.types ty ON c.user_type_id = ty.user_type_id
where ty.Name = 'uniqueidentifier'

Select @cnt =  count(1) from @TempTable
Declare @sql varchar(max), @table_name varchar(200), @column_name varchar(200) 
WHILE @ID <= @cnt
BEGIN

 SET @sql = ''
 SET @table_name = ''
 SET @column_name = ''
 Select @table_name = table_name,@column_name = column_name from @TempTable where ID = @ID
 SET @sql = 'select * from ' + @table_name + ' where ' + @column_name + ' = 123' --You can replace 123 by your text

 PRINT (@sql) -- You can write EXECUTE (@sql) here to execute it


 SET @ID = @ID + 1
END 

答案 1 :(得分:1)

这需要一些手动工作,但你可以这样:

select
    TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH,
    cmd = 'select ''' + table_name + ''' as tabname, ''' + column_name + ''' as colname, count(*) as rows from [' + TABLE_CATALOG + '].[' + TABLE_SCHEMA  + '].[' +  TABLE_NAME + '] where [' + COLUMN_NAME + '] like ''%%'' union all '
from INFORMATION_SCHEMA.COLUMNS
where 1=1
    and DATA_TYPE like '%char'
    and TABLE_NAME like '%%'

然后您只需执行生成的查询(更改选择以更好地满足您的需求并删除最后一个union all)。 同一个表中每列的结果将位于不同的行中,但您可以使用FOR XML PATH生成OR语句,这样它就不会返回搜索列重复的相同行。

如果您需要这是动态的,无需复制和粘贴,请检查此未记录的过程:

sp_msforeachtable @command1="declare @x Nvarchar(255); set @x='select count(*) from ?'; execute sp_executesql @x"

使用@command1information_schema.columns中构建您的查询,就像之前的示例一样。