The title is so straightforward...
Sometimes we know a value, but we don’t know which field the value is in the table in the library. We can use the following statement to query. For example, we query the field of "Zhang San" in that table:
DECLARE @cloumns VARCHAR(40);
DECLARE @tablename VARCHAR(40);
DECLARE @str VARCHAR(40);
DECLARE @counts INT;
DECLARE @sql NVARCHAR(2000);
DECLARE MyCursor CURSOR FOR
SELECT a.name AS Columns,
b.name AS TableName
FROM syscolumns a,
sysobjects b,
systypes c
WHERE a.id = b.id
AND b.type = 'U'
AND a.xtype = c.xtype
AND c.name LIKE '%char%';
SET @str = '张三';
OPEN MyCursor;
FETCH NEXT FROM MyCursor
INTO @cloumns,
@tablename;
WHILE (@@Fetch_Status = 0)
BEGIN
SET @sql = N'select @tmp_counts=count(*) from ' + @tablename + N' where ' + @cloumns + N' = ''' + @str + N'''';
EXECUTE sp_executesql @sql, N'@tmp_counts int out', @counts OUT;
IF @counts > 0
BEGIN
PRINT '表名为:' + @tablename + ',字段名为' + @cloumns;
END;
FETCH NEXT FROM MyCursor
INTO @cloumns,
@tablename;
END;
CLOSE MyCursor;
DEALLOCATE MyCursor;
result: