繁体   English   中英

在SQL Server中获取满足where条件的列名称

[英]Get column names in SQL server that satisfy a where condition on data

我只是在使用SQL服务器时有一个随机的疑问,我认为我可以在这里弄清楚它。 说-我有一个条件,我想找出数据库中满足我的where条件的所有列名称。

示例:-SQL-Server DB中有一些20-30个表。现在,我需要的是查询以查找具有“ Ritesh”作为数据字段的列名称列表。 首先,我不知道这是否真的可能。

我希望我很清楚。 请任何帮助将不胜感激。

谢谢。 里特什

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

--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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM