Solved

select * from table where all fields like '%value%'

Posted on 2011-03-11
18
703 Views
Last Modified: 2012-08-13
is there a way to write that query so I dont have to write it for every varchar column

or maybe make it one query  so I dont need to do 5 query
0
Comment
Question by:rgb192
  • 7
  • 4
  • 2
  • +4
18 Comments
 
LVL 37

Expert Comment

by:Neil Russell
ID: 35111574
Easy just

SELECT *
FROM tablename
WHERE field1 like '%value%'
AND field2 like '%value%'
AND field3 like '%value%'
AND field4 like '%value%'
AND field5 like '%value%'
0
 
LVL 8

Expert Comment

by:jawa29
ID: 35111671
Or if you want any column that contains your search then it will be.


SELECT *
FROM tablename
WHERE field1 like '%value%'
OR field2 like '%value%'
OR field3 like '%value%'
OR field4 like '%value%'
OR field5 like '%value%'

Jawa29

0
 
LVL 10

Expert Comment

by:Mez4343
ID: 35111698
Beat me to it, but maybe you need a working example and I used OR instead of AND because I assumed you wanted to return the row where any of the fields 1-5 contained your 'value'.
CREATE TABLE MyTable (Field1 varchar(max),Field2 varchar(max),
     Field3 varchar(max),Field4 varchar(max),Field5 varchar(max))
     
INSERT INTO MyTable Values('John Doe','John Smith','Fred Sanford','Jimmy Walker','Grady');
INSERT INTO MyTable Values('Jane Doe','Alice Smith','Amy Sanford','Karen Walker','Grady');

select * from MyTable
 WHERE Field1 LIKE '%John%' OR
	Field2 LIKE '%John%' OR
	Field3 LIKE '%John%' OR
	Field4 LIKE '%John%' OR
	Field5 LIKE '%John%'
	
	DROP TABLE MyTable

Open in new window

0
 
LVL 23

Expert Comment

by:wdosanjos
ID: 35111831
You can try something like this. It dynamically generates the SELECT based on the data dictionary.

DECLARE @schema nvarchar(50)
DECLARE @tname nvarchar(50)
DECLARE @like nvarchar(50)
DECLARE @cmd nvarchar(4000)

set @schema = 'dbo'
set @tname = 'YouTable'
set @like = '%value%'

set @cmd = 'SELECT * FROM [' + @schema + '].[' + @tname + '] WHERE 1 <> 1 ' +
           (SELECT (' OR [' + [COLUMN_NAME] + '] LIKE ''' + @like + '''')
			  FROM [INFORMATION_SCHEMA].[COLUMNS] c
			 WHERE c.TABLE_SCHEMA = @schema
			   AND c.TABLE_NAME = @tname 
			   AND c.DATA_TYPE IN ('varchar', 'nvarchar', 'char', 'nchar') 
			   FOR XML PATH(''))

exec (@cmd)

Open in new window

0
 
LVL 37

Expert Comment

by:Neil Russell
ID: 35111975
I used AND in the example as you said "select * from table where all fields like '%value%'"  i took that to mean litraly where ALL fields like.

Whether its AND or OR the concept is the same.
0
 
LVL 32

Expert Comment

by:ewangoya
ID: 35119298
You could try it this way
DECLARE @TableName varchar(128), @ColumnName varchar(128), @Search varchar(128)
DECLARE @Sql varchar(max)
SET @TableName = 'Customers'
SET @ColumnName = ''
SET @Sql = ''

SET @Search = '''Bon' + '%'''

WHILE @COLUMNNAME IS NOT NULL
BEGIN
	SET @COLUMNNAME = (
						SELECT MIN(QUOTENAME(COLUMN_NAME))
						FROM INFORMATION_SCHEMA.COLUMNS
						WHERE TABLE_NAME = @TABLENAME
						AND	DATA_TYPE IN ('CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR')
						AND	QUOTENAME(COLUMN_NAME) > @COLUMNNAME
					  )

	IF @COLUMNNAME IS NOT NULL
	BEGIN
	   IF @SQL = ''
	     SET @SQL = ' WHERE ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '
	   ELSE
	     SET @SQL =  @SQL + ' AND ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '  --or use "OR"

	END
END	
	
IF @Sql <> ''
BEGIN
	SET @Sql = 'SELECT * FROM ' + @TableName + ' ' + @Sql
	EXEC(@SQL)
END

Open in new window

0
 

Author Comment

by:rgb192
ID: 35152606
my existing table is named 'sitedata'

I do not want to create a new table

I want to search table 'sitedata'
0
 
LVL 32

Expert Comment

by:ewangoya
ID: 35152691

Replace customers with your table name
DECLARE @TableName varchar(128), @ColumnName varchar(128), @Search varchar(128)
DECLARE @Sql varchar(max)
SET @TableName = 'sitedata'
SET @ColumnName = ''
SET @Sql = ''

SET @Search = '''Bon' + '%'''

WHILE @COLUMNNAME IS NOT NULL
BEGIN
	SET @COLUMNNAME = (
						SELECT MIN(QUOTENAME(COLUMN_NAME))
						FROM INFORMATION_SCHEMA.COLUMNS
						WHERE TABLE_NAME = @TABLENAME
						AND	DATA_TYPE IN ('CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR')
						AND	QUOTENAME(COLUMN_NAME) > @COLUMNNAME
					  )

	IF @COLUMNNAME IS NOT NULL
	BEGIN
	   IF @SQL = ''
	     SET @SQL = ' WHERE ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '
	   ELSE
	     SET @SQL =  @SQL + ' AND ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '  --or use "OR"

	END
END	
	
IF @Sql <> ''
BEGIN
	SET @Sql = 'SELECT * FROM ' + @TableName + ' ' + @Sql
	EXEC(@SQL)
END

Open in new window

0
 

Author Comment

by:rgb192
ID: 35259573



DECLARE @schema nvarchar(50)
DECLARE @tname nvarchar(50)
DECLARE @like nvarchar(50)
DECLARE @cmd nvarchar(4000)

set @schema = 'dbo'
set @tname = 'YouTable'
set @like = '%value%'

set @cmd = 'SELECT * FROM [' + @schema + '].[' + @tname + '] WHERE 1 <> 1 ' +
           (SELECT (' OR [' + [COLUMN_NAME] + '] LIKE ''' + @like + '''')
                    FROM [INFORMATION_SCHEMA].[COLUMNS] c
                   WHERE c.TABLE_SCHEMA = @schema
                     AND c.TABLE_NAME = @tname
                     AND c.DATA_TYPE IN ('varchar', 'nvarchar', 'char', 'nchar')
                     FOR XML PATH(''))

exec (@cmd)

changing tname to sitedata, value to search term this query returns nothing














DECLARE @TableName varchar(128), @ColumnName varchar(128), @Search varchar(128)
DECLARE @Sql varchar(max)
SET @TableName = 'sitedata'
SET @ColumnName = ''
SET @Sql = ''

SET @Search = '''Bon' + '%'''

WHILE @COLUMNNAME IS NOT NULL
BEGIN
      SET @COLUMNNAME = (
                                    SELECT MIN(QUOTENAME(COLUMN_NAME))
                                    FROM INFORMATION_SCHEMA.COLUMNS
                                    WHERE TABLE_NAME = @TABLENAME
                                    AND      DATA_TYPE IN ('CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR')
                                    AND      QUOTENAME(COLUMN_NAME) > @COLUMNNAME
                                )

      IF @COLUMNNAME IS NOT NULL
      BEGIN
         IF @SQL = ''
           SET @SQL = ' WHERE ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '
         ELSE
           SET @SQL =  @SQL + ' AND ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '  --or use "OR"

      END
END      
      
IF @Sql <> ''
BEGIN
      SET @Sql = 'SELECT * FROM ' + @TableName + ' ' + @Sql
      EXEC(@SQL)
END





changing Bon to searchterm

this query always returns nothing
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 40

Expert Comment

by:Sharath
ID: 35263641
Do you really have the character columns in sitedate table? Try printing the sql and see.
DECLARE @TableName varchar(128), @ColumnName varchar(128), @Search varchar(128)
DECLARE @Sql varchar(max)
SET @TableName = 'sitedata'
SET @ColumnName = ''
SET @Sql = ''

SET @Search = '%Bon%'

WHILE @COLUMNNAME IS NOT NULL
BEGIN
      SET @COLUMNNAME = (
                                    SELECT MIN(QUOTENAME(COLUMN_NAME))
                                    FROM INFORMATION_SCHEMA.COLUMNS
                                    WHERE TABLE_NAME = @TABLENAME
                                    AND      DATA_TYPE IN ('CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR')
                                    AND      QUOTENAME(COLUMN_NAME) > @COLUMNNAME
                                )
print @ColumnName

      IF @COLUMNNAME IS NOT NULL
      BEGIN
         IF @SQL = ''
           SET @SQL = ' WHERE ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '
         ELSE
           SET @SQL =  @SQL + ' AND ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '  --or use "OR"

      END
END      
      
IF @Sql <> ''
BEGIN
      SET @Sql = 'SELECT * FROM ' + @TableName + ' ' + @Sql
      print(@SQL)
END

Open in new window

0
 

Author Comment

by:rgb192
ID: 35298545
[alternatecolors]
[pyxispackages]
[shippingtype]
[sunpackages]
 
SELECT * FROM sitedata  WHERE [alternatecolors] LIKE %Bon%  AND [pyxispackages] LIKE %Bon%  AND [shippingtype] LIKE %Bon%  AND [sunpackages] LIKE %Bon%
0
 
LVL 40

Expert Comment

by:Sharath
ID: 35300783
I think you need OR instead of AND. try this.
DECLARE @TableName varchar(128), @ColumnName varchar(128), @Search varchar(128)
DECLARE @Sql varchar(max)
SET @TableName = 'sitedata'
SET @ColumnName = ''
SET @Sql = ''

SET @Search = '%Bon%'

WHILE @COLUMNNAME IS NOT NULL
BEGIN
      SET @COLUMNNAME = (
                                    SELECT MIN(QUOTENAME(COLUMN_NAME))
                                    FROM INFORMATION_SCHEMA.COLUMNS
                                    WHERE TABLE_NAME = @TABLENAME
                                    AND      DATA_TYPE IN ('CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR')
                                    AND      QUOTENAME(COLUMN_NAME) > @COLUMNNAME
                                )
print @ColumnName

      IF @COLUMNNAME IS NOT NULL
      BEGIN
         IF @SQL = ''
           SET @SQL = ' WHERE ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '
         ELSE
           SET @SQL =  @SQL + ' OR ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '  --or use "OR"

      END
END      
      
IF @Sql <> ''
BEGIN
      SET @Sql = 'SELECT * FROM ' + @TableName + ' ' + @Sql
      EXEC(@SQL)
END

Open in new window

0
 

Author Comment

by:rgb192
ID: 35301626
[alternatecolors]
[pyxispackages]
[shippingtype]
[sunpackages]
 
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'Bon'.
0
 
LVL 32

Accepted Solution

by:
ewangoya earned 500 total points
ID: 35301769

The search string needs to be quoted, try this
DECLARE @TableName varchar(128), @ColumnName varchar(128), @Search varchar(128)
DECLARE @Sql varchar(max)
SET @TableName = 'sitedata'
SET @ColumnName = ''
SET @Sql = ''

SET @Search = '''%Bon%'''

WHILE @COLUMNNAME IS NOT NULL
BEGIN
      SET @COLUMNNAME = (
                                    SELECT MIN(QUOTENAME(COLUMN_NAME))
                                    FROM INFORMATION_SCHEMA.COLUMNS
                                    WHERE TABLE_NAME = @TABLENAME
                                    AND      DATA_TYPE IN ('CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR')
                                    AND      QUOTENAME(COLUMN_NAME) > @COLUMNNAME
                                )
print @ColumnName

      IF @COLUMNNAME IS NOT NULL
      BEGIN
         IF @SQL = ''
           SET @SQL = ' WHERE ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '
         ELSE
           SET @SQL =  @SQL + ' OR ' + @COLUMNNAME + ' LIKE ' + @SEARCH + ' '  --or use "OR"

      END
END      
      
IF @Sql <> ''
BEGIN
      SET @Sql = 'SELECT * FROM ' + @TableName + ' ' + @Sql
      EXEC(@SQL)
END

Open in new window

0
 

Author Comment

by:rgb192
ID: 35310044
no results

I changed
SET @Search = '''%n%'''

and there are 'n' in the table
0
 
LVL 32

Expert Comment

by:ewangoya
ID: 35311132

If you are using the "AND" operator, then all your character fields must satisfy the condition otherwise you will get no results back

If using "OR" yo definitely should be getting results if your search string exists in any of the character fields
0
 

Author Closing Comment

by:rgb192
ID: 35311731
tried with another table and it works
0
 

Author Comment

by:rgb192
ID: 35311733
in table 'sitedata' the fields where 'text'  so there were no results returned
0

Featured Post

Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

Join & Write a Comment

I've encountered valid database schemas that do not have a primary key.  For example, I use LogParser from Microsoft to push IIS logs into a SQL database table for processing and analysis.  However, occasionally due to user error or a scheduled task…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
This video discusses moving either the default database or any database to a new volume.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now