If performance does not matter, there is a fully generic approach implying XML XQuery.
The following will search through all attributes in the generated XML using contains()
, which is quite the same as LIKE
as you are using it in your sample.
DECLARE @stringToFind varchar(max)='owner';
SELECT
(
SELECT *
FROM sys.objects o
inner join sys.columns c ON c.object_id=o.object_id
for xml auto,type
).query('//*[@*[contains(.,sql:variable("@stringToFind"))]]');
In my case the string "owner" is found in one table's attribute as well as in several column's attributes.
The result in my case looks like this (shortend):
<c object_id="5" name="ownertype" column_id="2" system_type_id="48"
<c object_id="7" name="ownerid" column_id="3" system_type_id="127"
<o name="sysowners" object_id="27" schema_id="4" parent_object_id="
<c object_id="27" name="id" column_id="1" system_type_id="56" use
<c object_id="27" name="name" column_id="2" system_type_id="231"
<c object_id="27" name="type" column_id="3" system_type_id="175"
<c object_id="27" name="sid" column_id="4" system_type_id="165" u
<c object_id="27" name="password" column_id="5" system_type_id="1
<c object_id="27" name="dfltsch" column_id="6" system_type_id="23
<c object_id="27" name="status" column_id="7" system_type_id="56"
<c object_id="27" name="created" column_id="8" system_type_id="61
<c object_id="27" name="modified" column_id="9" system_type_id="6
<c object_id="27" name="deflanguage" column_id="10" system_type_i
</o>
The idea in short:
- Using
FOR XML AUTO
will created XML elements with the tables aliases as tags, while the attributes are the values.
- The XQuery expressions will look through any attribute anywhere in the XML.
- The predicate will filter for elements answering the predicate.
- Using
sql:variable()
allows to introduce a variable's value into the XQuery.
This is - of course! - limited.
- The performance will be low.
- Using
*
will include any column, even huge BLOBs.
- Your approach creating a SQL-statement dynamically is probably better, but this depends on your needs...