0

In T-SQL, if just know value of one column say: 'Ferrari', then is it possible to know the column name table name, database name using any query or trick?

2
  • Can you post an example? Do you mean that a table contains a row where one of the columns has the value Ferrari and you want to know what column name and table contains this value? Commented Dec 7, 2012 at 11:05
  • Do you mean you have a value "Ferrari" and you need to find where it is stored? Commented Dec 7, 2012 at 11:57

1 Answer 1

1

Not saying this is optimal at all but this will find the table-name, schema and columnname of a column with the value 'Ferrari'

-- I will use a PROC so we create a table-type
create type Meta as table (rid int identity primary key, ts varchar(100), tn varchar(100), cn varchar(100))

--Now create the proc
    create proc [dbo].[foo] 
(   
    @t Meta readonly,
    @v varchar(50)
)
AS
begin
    declare @max int
    declare @c bit
    declare @i int
    declare @ts varchar(100)
    declare @tn varchar(100)
    declare @cn varchar(100)
    declare @q nvarchar(max)

    set @max = (select max(rid) from @t);
    set @c = 0;
    set @i = 0;
    while(@i <= @max)
    begin
        set @i += 1;
        select @ts = ts, @tn = tn, @cn = cn from @t where rid = @i;
        set @q = N'select @p0 = 1 from ' + @ts + '.' + @tn + ' where ' + @cn + '=@p1;';
        exec sp_executesql @q, N'@p0 bit out, @p1 varchar(50)', @p1=@v,@p0=@c out
        if(@c > 0)
        begin
            set @c = 1;
            break;
        end
    end

    if(@c = 1)
        select @ts + '.' + @tn + '.' + @cn;
    else
        select null;
end

-- Now use it
declare @v varchar(50)
set @v = 'Ferrari'

declare @t Meta
insert into @t
select
    c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS c
where
    c.DATA_TYPE like '%varchar'
    and c.CHARACTER_MAXIMUM_LENGTH >= len(@v)

exec dbo.foo @t = @t, @v = @v
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.