如何在SQL Server中使用列的值查找列和表名?

时间:2012-12-07 11:01:17

标签: sql-server tsql

在T-SQL中,如果只知道一列的值说:' Ferrari',那么是否可以使用任何查询或技巧知道列名表名,数据库名?

1 个答案:

答案 0 :(得分:1)

并不是说这是最优的,但是会找到值为'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