如何在t-sql存储过程中检索相应表和列的行值

时间:2013-10-16 11:57:46

标签: sql sql-server tsql stored-procedures

我正在使用一个存储过程来搜索整个数据库,并返回ID字段中的表名,列名和值。我很乐意使用Table-name和column-name进行搜索,但不是在获取相应的ID。

 table-name:Task_typen

 task_ID  task      name
  1       reading   read_task
  2       writing   write_task
  3       sleeping  sleep_task

示例:当我搜索字符串'writing'

表名,即“Task_typen”和 列名“任务” 输出,但我需要task_ID中相应的ID为字符串'写',即2也应与table-name和column-name一起输出

存储过程可以在下面找到

CREATE TABLE myTable99 (TABLE_NAME sysname, COLUMN_NAME sysname, Occurs int)
GO

SET NOCOUNT ON

DECLARE @SQL varchar(8000),
 @TABLE_NAME sysname, 
 @COLUMN_NAME sysname,
 @Sargable varchar(80), 
 @Count int

SELECT @Sargable = 'PS'

DECLARE insaneCursor CURSOR FOR 
SELECT c.TABLE_NAME, c.COLUMN_NAME 
  FROM INFORMATION_SCHEMA.Columns c INNER JOIN INFORMATION_SCHEMA.Tables t
    ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
 WHERE c.DATA_TYPE IN ('char','nchar','varchar','nvarchar','text','ntext')
   AND t.TABLE_TYPE = 'BASE TABLE'

OPEN insaneCursor

FETCH NEXT FROM insaneCursor INTO @TABLE_NAME, @COLUMN_NAME

WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @SQL = 'INSERT INTO myTable99 (TABLE_NAME, COLUMN_NAME, Occurs) SELECT '
            + '''' +  @TABLE_NAME + '''' + ','
            + '''' + @COLUMN_NAME + '''' + ','
            + 'COUNT(*) FROM [' + @TABLE_NAME  
            + '] WHERE [' + @COLUMN_NAME + '] Like '
            + ''''+ '%' + @Sargable + '%' + ''''
    --SELECT @SQL
    EXEC(@SQL)
    IF @@ERROR <> 0 
    ------ <> means Not Equal To
        BEGIN 
            SELECT @SQL
            SELECT * FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = @TABLE_NAME
            GOTO Error
        END 
    FETCH NEXT FROM insaneCursor INTO @TABLE_NAME, @COLUMN_NAME
END

SELECT * FROM myTable99 WHERE Occurs <> 0 


Error:
CLOSE insaneCursor
DEALLOCATE insaneCursor

GO

DROP TABLE myTable99
GO

SET NOCOUNT OFF

1 个答案:

答案 0 :(得分:0)

不要使用游标,这样的东西应该可以正常工作:

SET NOCOUNT ON

SELECT @SQL = @SQL + 'SELECT '''+c.TABLE_NAME+''' AS [TAB], '''+c.COLUMN_NAME+''' AS [COL], COUNT(*) AS [COUNT] FROM '+c.TABLE_NAME+' WHERE '+c.COLUMN_NAME+' = '''+@SEARCHSTR+''' UNION ALL ' 
  FROM INFORMATION_SCHEMA.Columns c INNER JOIN INFORMATION_SCHEMA.Tables t
    ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
 WHERE c.DATA_TYPE IN ('char','varchar','text')
   AND t.TABLE_TYPE = 'BASE TABLE'

SELECT @SQL = @SQL + 'SELECT '''+c.TABLE_NAME+''' AS [TAB], '''+c.COLUMN_NAME+''' AS [COL], COUNT(*) AS [COUNT] FROM '+c.TABLE_NAME+' WHERE '+c.COLUMN_NAME+' = N'''+@SEARCHSTR+''' UNION ALL ' 
  FROM INFORMATION_SCHEMA.Columns c INNER JOIN INFORMATION_SCHEMA.Tables t
    ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
 WHERE c.DATA_TYPE IN ('nchar','nvarchar','ntext')
   AND t.TABLE_TYPE = 'BASE TABLE'

SELECT @SQL = SQL + 'SELECT ''END'' AS [TAB], ''END'' AS [COL], 0 AS [COUNT]'

EXEC(@SQL)