Sometimes we want to know by a value which table and which field from the database, search on the Internet, find a better way to achieve through a stored procedure. Just pass in a value that you want to find, and you can query the table and field name where the value resides.
The premise is to put this stored procedure in the database you are querying.
Note: The 1 step is to create a stored procedure that can be used in any database, and the 2 step is to call it to find all the columns involved in the database and the corresponding tables. It's very convenient to just need one data.
First, click on the new query, the upper left corner to choose their own database, and then copy the following paragraph and then runCREATE 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
Second, then, enter EXEC [Sp_findvalueindb] ' Here is what you want to check the content value ' run on OK
For example, to query the value ' BBQ CHIC SW ', the results are as follows:
Returns three records indicating that the value exists in three tables, _dts_menudef, G_dts_menudef, and g_recipe, with field names name1, name1, name, respectively.
Very useful.
SQL database only one data, query to the table and column name