SQL2008 to find a column in a database if a value exists

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.