Wednesday, November 24, 2010

Search String From Passing Table Find All Columns No Need to Specify


This Code will Help to Find the string from all the Existing columns from passed table.
You Need to Pass only tableName and searchString


USE [dbCMS]
GO
/****** Object: UserDefinedFunction [dbo].[fnSearchQuery] Script Date: 11/24/2010 17:16:51 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Function [dbo].[fnModuleSearchQuery](@Table_Name SYSNAME,@Search_String VARCHAR(100))
Returns Varchar(Max) As
BEGIN
Declare @Query_String Varchar(MAX); /*For Store the Full String*/
Set @Query_String = '';
Declare @Column_Name SYSNAME,
@Sql_String Varchar(MAX)

/*For Store All Column On the Table*/
Declare Column_Cur Cursor For SELECT Name FROM sys.columns
WHERE object_id = (Select object_id from sys.objects Where Name = @Table_Name)
AND system_type_id IN (167, 175, 231, 239)

Open Column_Cur
Fetch Next From Column_Cur INTO @Column_Name
WHILE (@@FETCH_STATUS = 0)
BEGIN
Set @Sql_String = 'SELECT * FROM ' + @Table_Name + ' WHERE '
+ @Column_Name + ' LIKE ''%' + @Search_String + '%'''

Set @Query_String = @Query_String + @Sql_String + ' UNION '
--Execute(@sql_string)
--Print @sql_string
FETCH NEXT FROM Column_Cur INTO @Column_Name
END

CLOSE Column_Cur
DEALLOCATE Column_Cur
Return (Substring(@Query_String,0,Len(@Query_String)-4))
END


--============For Display on the Records Need to call like this ==========

Declare @String varchar(MAX)
Select @String = dbo.fnSearchQuery('SiteDropBox','Bhilai')
Exec(@String)

No comments:

Post a Comment