【发布时间】:2018-12-23 03:44:43
【问题描述】:
我正在使用 SQL Server。我有很多表,我需要找到一个特定的值并返回该值存在于哪个表中。我知道该值所在的列。
我的方法:首先我使用游标获取所有可以具有该列名的表。其次,我逐个遍历游标,使用Where 子句对每个表执行选择查询以查找值。如果值在那个表中,我应该打印“found in table”。
我需要在循环中放置一个查询,该查询应该打印出该值所在的表名。我从游标中获取表名,我已经有了列名和值,但无法编写动态 SQL 查询。请帮我写动态查询
DECLARE column_cursor CURSOR FOR
SELECT t.name AS 'TableName'
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%Agreement_Number%'
ORDER BY TableName;
DECLARE @table_name NVARCHAR(80), @column_value NVARCHAR(30) ;
//@table_name --> table from the cursor
//@column_value --> the value that I am searching for
OPEN column_cursor
FETCH NEXT FROM column_cursor INTO @table_name
WHILE @@FETCH_STATUS = 0
BEGIN
//Not able to put the logic here .
//I should be able to iterate over each table and check for the column_value and print if its exists in the table or not
FETCH NEXT FROM column_cursor INTO @column_name, @table_name
END
【问题讨论】:
-
我们已经回答了这样的问题stackoverflow.com/questions/9679997/…。请参考这里。
标签: sql-server ssms