Find out where a field in a SQL Server database

Source: Internet
Author: User

Sometimes we want to know by a value that this value comes from which table and which field in the database, search the Web and find a better way to implement it through a stored procedure. You just need to pass in a value you want to find, and you can query the table and field names that the value is in.

The prerequisite is to place this stored procedure in the queried database.

CREATE PROCEDURE [dbo]. [SP_FINDVALUEINDB]

(

@value VARCHAR (1024)

)

As

BEGIN

---SET NOCOUNT on added to prevent extra result sets from

--interfering with SELECT statements.

SET NOCOUNT on;

DECLARE @sql VARCHAR (1024)

DECLARE @table VARCHAR (64)

DECLARE @column VARCHAR (64)

CREATE TABLE #t (

TableName VARCHAR (64),

ColumnName VARCHAR (64)

)

DECLARE TABLES CURSOR

For

SELECT O.name, C.name

From syscolumns C

INNER JOIN sysobjects o on c.id = o.id

WHERE o.type = ' U ' and C.xtype in (167, 175, 231, 239)

Order by O.name, C.name

OPEN TABLES

FETCH NEXT from TABLES

Into @table, @column

While @ @FETCH_STATUS = 0

BEGIN

SET @sql = ' IF EXISTS (SELECT NULL from [' + @table + '] '

SET @sql = @sql + ' WHERE RTRIM (LTRIM ([' + @column + ']) like '% ' + @value + '% ') '

SET @sql = @sql + ' INSERT into #t VALUES (' + @table + ', ' "

SET @sql = @sql + @column + ') '

EXEC (@sql)

FETCH NEXT from TABLES

Into @table, @column

End

Close TABLES

Deallocate TABLES

SELECT *

From #t

DROP TABLE #t

End

Related Article

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.