在数据库中查找特定数据

时间:2018-09-19 17:30:05

标签: sql sql-server

我有以下查询,可从中查询数据库中的给定列名。但是,我也希望能够显示列的第一行,因此我可以看到列中包含哪些数据。

有有效的方法吗?

SELECT      c.name  AS 'ColumnName'
           ,t.name AS 'TableName'
FROM        sys.columns c
JOIN        sys.tables  t   ON c.object_id = t.object_id
WHERE       c.name LIKE '%Insert Data Here%'
ORDER BY    TableName
           ,ColumnName;

2 个答案:

答案 0 :(得分:2)

您可以将选择构建到变量中并按如下所示执行它。根据您的数据类型,您可能会遇到问题(例如,根据我的搜索值,我有一列会显示此消息

  

不允许从数据类型图像到varchar(max)的显式转换。

但是,对于普通数据类型,这应该对您有用:

DECLARE @searchKey NVARCHAR(100) = 'name' --this is what you're looking for in the column name
    , @selectCommand NVARCHAR(MAX)

SELECT @selectCommand = COALESCE(@selectCommand + ' union all ','') + 'select top 1 '''+ i.COLUMN_NAME+''' AS ColumnName, ''['+ i.TABLE_SCHEMA+'].['+ i.TABLE_NAME+']'' AS TableName, try_convert(varchar(max),'+ i.COLUMN_NAME+') AS SampleData FROM ['+ i.TABLE_SCHEMA+'].['+ i.TABLE_NAME+'] '
FROM INFORMATION_SCHEMA.COLUMNS i 
WHERE i.COLUMN_NAME LIKE N'%'+@searchKey+'%'
EXEC(@selectCommand)

结果看起来像这样,其@searchKey为'name':

ColumnName   TableName              SampleData
name         [dbo].[table_1]        person 1
NAME         [dbo].[asffaef]        rose
name         [dbo].[tablefeoe]      ashely
DatabaseName [dbo].[Untitled - 3]   NULL
LoginName    [dbo].[Untitled - 3]   NULL

答案 1 :(得分:0)

我本来以为您可以在单个dymaic sql语句中完成此操作,但是后来意识到这是行不通的。因此,不幸的是,这是您必须将cursordynamic sql一起使用的情况之一:

CREATE TABLE #Results (tableName varchar(100), columnName varchar(100), val varchar(max))

DECLARE @SQLString nvarchar(500) 
DECLARE @TableName nvarchar(100)
DECLARE @ColumnName nvarchar(100)

DECLARE tables_columns_cursor CURSOR FOR
SELECT      c.name  AS ColumnName
           ,t.name AS TableName
FROM        sys.columns c
JOIN        sys.tables  t   ON c.object_id = t.object_id
WHERE       c.name LIKE '%Insert Data Here%'
ORDER BY    TableName
           ,ColumnName;

OPEN tables_columns_cursor
FETCH NEXT FROM tables_columns_cursor INTO @ColumnName, @TableName

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @SQLString = 'INSERT INTO #Results 
                      SELECT TOP 1 ''' + @ColumnName + ''' AS ColumnName
                           , ''' + @TableName + ''' AS TableName
                           , ' + @ColumnName + ' 
                      FROM ' + @TableName

    EXECUTE sp_executesql @SQLString

    FETCH NEXT FROM tables_columns_cursor INTO @ColumnName, @TableName
END
CLOSE tables_columns_cursor
DEALLOCATE tables_columns_cursor

SELECT * FROM #Results
DROP TABLE #Results