I'm trying to create a stored procedure that will search all user created tables of a database for a search string.
I found this stored procedure that I'd like to start off with and build on.
http://vyaskn.tripod.com/search_all_columns_in_all_tables.htm
The only problem is entering a datetime into the search will always return nothing.
How can I modify this to search for dates as well?
Lines of interest:
CREATE PROC SearchAllTables
@SearchStr nvarchar(100)
AS
....
SET @SearchStr2 = CASE WHEN ISDATE(@SearchStr)=0
THEN QUOTENAME('%' + @SearchStr + '%','''')
ELSE @SearchStr END
....
--Here's where the comparison is made. This comparison works for string and numeric types but not datetime
DECLARE @sql nvarchar(max)
IF ISDATE(@SearchStr) = 0
BEGIN
SET @sql = 'INSERT INTO #Results SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
END
ELSE IF ISDATE(@SearchStr) = 1
BEGIN
SET @sql = 'INSERT INTO #Results SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE DATEDIFF(day, CONVERT(datetime, '+ @ColumnName + ', 103), ' + @SearchStr+ ') = 0'
END
PRINT @sql
EXEC sp_ExecuteSQL @sql
GO
I get a conversion error. I need this stored procedure to work with all 3 types of data string, numeric, and date.
Conversion failed when converting date and/or time from character string.
Thank you
your date field is a datetime?
you should traet it like this:
declare @SearchStr datetime
set @SearchStr = convert(datetime, '2012-09-10', 103) –- dd/mm/yyyy
and the where part like this:
'WHERE Datediff(day, CONVERT(datetime, '+ @ColumnName + ', 103), ' + @SearchStr+') = 0'
I think this should work