Original: SQL2008 find a value in a database column
SQL2008 to find a column in a database if a value exists
--SQL2008 to find a value in a column in a databaseCreate procspfind_column_in_db (@type int,--Type: 1 for text type, 2 for numeric type @str nvarchar( -)--name to search for) as --create temporary tables to hold results Create Table#tbl (PKint Identity Primary Key, tbl sysname,col sysname)Declare @tbl nvarchar( -),@colsysname@sql nvarchar( +) if @type=1 begin DeclareCurtablecursorFast_forward for Select '['+Schema_name (schema_id)+']. ['+O.name+']'TableName,'['+C.name+']'ColumnName fromSys.columns CInner JoinSys.objects o onC.object_id=O.object_id whereO.type_desc='user_table' anduser_type_idinch(167,175,231,239, *, About) End Else begin DeclareCurtablecursorFast_forward for Select '['+Schema_name (schema_id)+']. ['+O.name+']'TableName,'['+C.name+']'ColumnName fromSys.columns CInner JoinSys.objects o onC.object_id=O.object_id whereO.type_desc='user_table' anduser_type_idinch( About, -, the, -, -, +,106,108,122) End OpencurtableFetch Next fromCurtable into @tbl,@col while @ @FETCH_STATUS=0 begin Set @sql='if exists (SELECT * from'+@tbl+'where' if @type=1 begin Set @sql += @col + ' like"'%'+@str +'%"')' End Else begin Set @sql +=@col + 'In ('+@str+'))' End Set @sql += 'INSERT #TBL (tbl,col) VALUES (" "+@tbl+" "," "+@col+" ")' --Print @sql exec(@sql) Fetch Next fromCurtable into @tbl,@col End ClosecurtabledeallocatecurtableSelect * from#tbl--using the example, query the column in the library that has the AAA value:execspfind_column_in_db1,'AAA'
SQL2008 to find a column in a database if a value exists