在SQL server中获取满足数据where条件的列名



我只是有一个随机的怀疑,而与SQL-server工作,我认为我可以得到它澄清在这里。比如说-我有一个条件,我想找出数据库中满足我的where条件的所有列名。

例子:-一个SQL-Server数据库中大约有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

最新更新