Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql select rows containing part of string

Tags:

sql

tsql

I want to write a comparation procedure (t-sql) for site seo.

I have a table with field 'url' (nvarchar()) that contain a part of site url's. Ex: 'mysyte.com/?id=2'. Also this table for each url contains metadata, that i need to extract.

The main problem is that full url on site looks like 'mysyte.com/?id=2&region=0&page=1', and i just need to ignore everething, except url in table:

I mean: 'mysyte.com/?id=2' => is a part of 'mysyte.com/?id=2&region=0&page=1'

like image 523
Maxim Avatar asked Apr 12 '10 11:04

Maxim


People also ask

How do you check if a substring is present in a string in SQL?

SQL Server CHARINDEX() Function The CHARINDEX() function searches for a substring in a string, and returns the position. If the substring is not found, this function returns 0. Note: This function performs a case-insensitive search.

Is there a Contains function in SQL?

CONTAINS is a predicate used in the WHERE clause of a Transact-SQL SELECT statement to perform SQL Server full-text search on full-text indexed columns containing character-based data types. CONTAINS can search for: A word or phrase. The prefix of a word or phrase.

Which function is used to extract a part of the string in SQL?

The SUBSTRING() function extracts a substring from a string (starting at any position).


2 Answers

You can use the LIKE operator to compare the content of a T-SQL string, e.g.

SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'

The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".

like image 88
WiseGuyEh Avatar answered Oct 05 '22 08:10

WiseGuyEh


SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2&region=0&page=1', LEN(URL))

Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx

like image 35
Jonathan Avatar answered Oct 05 '22 08:10

Jonathan