获取SQL服务器中满足数据where条件的列名称

时间:2014-06-11 05:33:10

标签: sql sql-server

我在使用SQL-server时遇到了一个随机的疑问,我认为我可以在这里澄清一下。 说 - 我有一个条件,我想找出数据库中的所有列名称满足我的数据的where条件。

实施例: - SQL-Server DB中有大约20-30个表。现在我只需要一个查询来查找列中包含“Ritesh”作为数据字段的列名列表。 我不知道最初是否真的有可能。

我希望我很清楚。请,任何帮助将非常感谢。

谢谢。 仅限Ritesh。

1 个答案:

答案 0 :(得分:2)

这应该有效,但要注意,这需要一段时间才能在大型数据库中执行。我假设搜索字符串可能只是所包含数据的一部分,并且使用通配符。我觉得这纯粹是学术性的,因为我无法想象一个场景,需要这样做。

--you need to iterate the whole columns of entire table to find the matched record
--another thing is that you need dynamic sql to find the table name

DECLARE @Value varchar(50) --value for that find the column Name
SET @Value = 'Ritesh'

CREATE TABLE #Table
(
    TableName Varchar(500),ColumnName Varchar(500),
    Id int Identity(1,1) --use for iteration
)
CREATE TABLE #Results
(
TableName varchar(500),
ColumnName varchar(500)
)
INSERT INTO #Table
    SELECT
        TABLE_SCHEMA + '.' + TABLE_NAME AS TableNam,
        Column_name AS ColumnName
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE Data_type IN ('char', 'nchar', 'varchar', 'nvarchar')
--change the datatype based on the datatype of sample data you provide
-- also remember to change the wildcard, if the input datatype is not a string

DECLARE @Count Int --total record to iterated
SET @Count = 0;


SELECT
    @Count = COUNT(*)
FROM #Table


DECLARE @I int --initial value one to iterate
SET @I = 1;


DECLARE @TableName varchar(500)
SET @TableName = ''
DECLARE @ColumnName varchar(500)
SET @ColumnName = ''


DECLARE @Str nvarchar(1000)
SET @Str = ''
DECLARE @param nvarchar(1000)
SET @param = ''


DECLARE @TableNameFound varchar(max)
SET @TableNameFound = ''


DECLARE @Found bit
SET @Found = 0;

WHILE @I<=@Count
BEGIN

SET @Found = 0;
SELECT
    @TableName = TableName,
    @ColumnName = ColumnName
FROM #Table
WHERE Id = @I;
SET @param = '@TableName varchar(500),@ColumnName varchar(500),@Value varchar(50),@TableNameFound varchar(max),@Found bit output'
SET @str = 'Select @Found=1 From ' + @TableName + ' where ' + @ColumnName + ' Like ' + '''' + '%' + @Value + '%' + ''''

-- here we are using tablename and actual value to find in table
EXEC sp_executesql  @str,
                    @param,
                    @TableName,
                    @ColumnName,
                    @Value,
                    @TableNameFound,
                    @Found OUTPUT

    IF @Found=1
    BEGIN
    INSERT INTO #Results (TableName, ColumnName)
    SELECT
        @TableName,
        @ColumnName
    END

--increment value of @I
SET @I = @I + 1;
END

--Display Results
SELECT * FROM #Results

--Clean Up
DROP TABLE #Table
DROP TABLE #Results