This might do it for you. Note that if you have a lot of tables/columns this might take quite a while. If you're not searching in (N)VARCHAR
columns, you might want to add those types to the c.DATA_TYPE NOT IN(...
clause. Or any other type you're not looking in (like FLOAT
or DECIMAL
).
SET NOCOUNT ON;
DECLARE @value NVARCHAR(MAX)='123';
CREATE TABLE #found(table_name SYSNAME,column_name SYSNAME);
DECLARE @sql NVARCHAR(MAX)=(
SELECT
'INSERT INTO #found(table_name,column_name) ' +
'SELECT TOP 1 '+
'table_name='''+REPLACE(t.TABLE_NAME,'''','''''')+''','+
'column_name='''+REPLACE(c.COLUMN_NAME,'''','''''')+''' '+
'FROM '+
QUOTENAME(t.TABLE_SCHEMA)+'.'+QUOTENAME(t.TABLE_NAME)+' '+
'WHERE '+
QUOTENAME(c.COLUMN_NAME)+'='''+REPLACE(@value,'''','''''')+''';'
FROM
INFORMATION_SCHEMA.TABLES AS t
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS c ON
c.TABLE_SCHEMA=t.TABLE_SCHEMA AND
c.TABLE_NAME=t.TABLE_NAME
WHERE
t.TABLE_TYPE='BASE TABLE' AND
c.DATA_TYPE NOT IN('BIT','NTEXT','TEXT','IMAGE','BINARY','VARBINARY','DATETIME','DATE','DATETIME2','TIME','SMALLDATETIME','DATETIMEOFFSET')
FOR XML
PATH('')
);
EXECUTE (@sql);
SELECT * FROM #found ORDER BY table_name,column_name;
DROP TABLE #found;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…