Click here to Skip to main content
15,906,626 members
Please Sign up or sign in to vote.
3.86/5 (3 votes)
sir/mam
i am a fresher and i have a question to ask that is
i have 30 tables in my database suppose

Table Name : District1,District2,District3......upto 30
Columns : Distid int,Distname varchar(30),Header varchar(100),News varchar(MAX)


in 30 tables Header is common column
my requirement is to search a given sentence (say "CM resigns today") which is present in one of the 30 table and

want to know the table name where it is present?
Posted
Updated 27-Oct-13 23:56pm
v2

SQL
declare  @Table table(Id int identity, Name varchar(100));

insert @Table(Name)
	(select t.TABLE_NAME from INFORMATION_SCHEMA.TABLES t
	join INFORMATION_SCHEMA.COLUMNS c on c.TABLE_NAME = t.TABLE_NAME
	where c.COLUMN_NAME = 'Header');

declare @Index int =0;
while(1 =1 )
begin
	set @Index += 1;
	declare @TableName varchar(100) = (select Name from @Table where id = @Index);

	if @TableName is null
		break;
	exec('select * from ' + @TableName + ' where Header = ''CM resigns today''');
end


create a table variable, it load table name which have column 'Header'. Iterate the table variable and execute dynamic sql where Header column contain 'CM resigns today'.
 
Share this answer
 
Try this as below

SQL
DECLARE @Sql nVarchar(max)
DECLARE @Col Varchar(max)
DECLARE @ST Varchar(max)
DECLARE @Table Varchar(MAX)
DECLARE @Result Varchar(MAX)

SET @Col = 'AccountNumber'
SET @ST = 'AUSTRALI0001'

SELECT TABLE_SCHEMA+'.'+TABLE_NAME as TableName INTO #Temp FROM INFORMATION_SCHEMA.COLUMNS Where COLUMN_NAME = @Col

DECLARE Table_Cur cursor FOR
SELECT TableName FROM #Temp

OPEN Table_Cur
FETCH NEXT FROM Table_Cur INTO @Table

WHILE @@FETCH_STATUS = 0
BEGIN
SET @Sql = 'Select '+@Col+' From '+@Table+' Where '+@Col+' = '''+@ST+''''
exec sp_executesql @Sql, N'@x int out', @Result out

END

CLOSE Table_Cur
DEALLOCATE Table_Cur

Drop TABLE #Temp
 
Share this answer
 
Hi!!!!
use this query
SQL
SELECT Header 
FROM sys.Tables where Header="CM resigns today"
 
Share this answer
 
Comments
raxhemanth 28-Oct-13 6:17am    
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Header'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Header'.
getting this error even i enter correct column name
raxhemanth 28-Oct-13 6:17am    
thanks for your quick response.
Shubham Choudhary 28-Oct-13 6:20am    
sorry @raxhemanth
try
SELECT *
FROM sys.Tables where Header="CM resigns today"

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900