Comparing 2 tables in SQL Server - sql-server

I have 2 SQL tables, one contains 2 columns, First Name and Last Name and the other has a column called NAME which has full names in it. I am trying to find if any of the values from the Last Name column in table1 can be found in the NAME column of table2. So far I have tried the following query without much success:
SELECT * FROM table1
CROSS APPLY
(SELECT * FROM table2 WHERE ('%'+table1.[Last Name]+'%' LIKE table2.NAME)) table2

I am not sure, but I think this works:
SELECT *
FROM table1
WHERE ISNULL((SELECT TOP(1) 1 FROM tabl2 WHERE Name LIKE '%' + table1.LastName + '%'), 0)= 1
This query's accuracy can suffer in case of similar first and last names. You can add white spaces for better accuracy: LIKE '% table1.LastName %'.

Related

Add names to a column that doesn't have a name already in SQL Server

I created a a stored procedure that returns a table that looks like this:
(No column name) (No column name)
2 4
The table has no name, but I'll call the procedure, "proc".
How would I change the name of the two columns that currently have no name, so basically:
ColA AnotherColumn
---------------------
2 4
You need to alias them. This happens in a few cases, but often with aggregate functions and sub-queries
select
sum(someColumn) as NewColumnName
,(select top 1 something From somewhere) ThisColumn --notice the AS is optional
from YourTable
Another method which isn't ANSI standard is using =
select
NewColumnName = sum(someColumn)
,ThisColumn = (select top 1 something From somewhere)
from YourTable

Search SQL Server string for values from another table

I have a table with column name that has random characters before and after the name ie:
Table A:
Name
-----------------
asd4345JONlkj345
.;lidDavidlksd$
and I have another table in same DB that has the names ie:
Table B:
Name
------
David
Jon
This goes on like this for 30k rows or I'd just hardcode something really quick. I want to search each string in Table A 'Name' column for each value from Table B, and if found return the name in a new column.
I have a feeling this will be a UDF, which is fine, I'm just unsure how to use patindex in this scenario, or if that is even the right approach.
You only need the LIKE operator for this:
select *
from TableA
inner join TableB on TableA.Name like '%' + TableB.Name + '%'
select B.Name, A.Name from tableA A inner join join tableB B
on rtrim(ltrim(B.Name)) like '%' + rtrim(ltrim(A.Name)) + '%'

SQL Server Join columns with wildcard

I need to find a way to join two tables based using the columns' names with wild cards. This is the scenario I have:
CREATE TABLE #table1
(
AuthCode varchar(10)
)
INSERT INTO #table1
VALUES ('52201')
SELECT * FROM #table1
JOIN bilact
ON #table1.AuthCode = bilact.byAuthCode
In bilact table, the auth code is 005221 (the field is a varchar) and when I run the above query, it does not return any result.
The situation I am running into is so complicated and i do not want to explain why I must do it this way cause it is the only way that will work. Is there a way I can add the wild card with the column name in a join? Thank you.
Assuming you want one column to be the substring of another:
SELECT * FROM #table1
JOIN bilact
ON str(bilact.byAuthCode) LIKE '%' + #table1.AuthCode + '%'
or, if you need to match a substring in either table
SELECT DISTINCT * FROM #table1
JOIN bilact
ON str(bilact.byAuthCode) LIKE '%' + #table1.AuthCode + '%'
OR #table1.byAuthCode LIKE '%' + str(bilact.AuthCode) + '%'
You can remove the str()'s if both columns are varchars or some form of string field.
Otherwise, you need to decide what the longest common substring the 2 columns need in common, and in the join, iterate over every possible substring of one of the columns and do a like as above with the other column against it.

sql server 2005 - select records from tbl A contained WITHIN a text field of tbl B

I'm trying to work out a SQL Select in MS SQL 2005, to do the following:
TABLE_A contains a list of keywords... asparagus, beetroot, beans, egg plant etc (x200).
TABLE_B contains a record with some long free text (approx 4000 chars)...
I know what record within TABLE_B I am selecting (byID).
However I need to get a shortlist of records from TABLE_A that are contained WITHIN the text of the record in TABLE_B.
I'm wondering if SQLs CONTAINS function is uselful... but maybe not.
This needs to be a super quick query.
Cheers
It will never be super quick because of the LIKE and wildcard at each end. You can not index it and there are no whizzy tricks. However, because you have already filtered TableB then it should be acceptable. If you had a million rows in tableB, you could go for coffee while it ran
SELECT
A.KeyWordColumn
FROM
TableA A
JOIN
TableB B ON B.BigTextColumn LIKE '%' + A.KeyWordColumn+ '%'
WHERE
B.ByID = #ID --or constant etc
CONTAINS can be used if you have full text indexing: but not for a normal SQL query
I would try this
select keyword from table_a, table_b
where table_b.text like '%' + keyword + '%'
and table_b.Id = '111'

Using the SQL LIKE operator with %%

I had a requirement to create a query in SQL Server where the search condition would include/exclude a table based on user input.
Say I have two tables, TABLE_A and TABLE_B with columns KEYCOLUMN_A and COLUMN_A in TABLE_A and columns FKCOLUMN_B and COLUMN_B in TABLE_B.
And a query like:
SELECT TABLE_A.* FROM TABLE_A, TABLE_B WHERE TABLE_A.KEYCOLUMN_A = TABLE_B.FKCOLUMN_B
AND TABLE_A.COLUMN_A LIKE '%SEARCH%' AND TABLE_B.COLUMN_B LIKE '%SEARCH2%'
Now if the user does not input SEARCH2, I don't need to search TABLE_B. But this would mean an IF ELSE clause. And as the number of "optional" tables in the query increases, the permutations and combinations would also increase and there will be many IF and ELSE statements.
Instead I decided to keep the statement as it is. So if SEARCH2 is empty, the query will effectively become:
SELECT * FROM TABLE_A, TABLE_B WHERE TABLE_A.KEYCOLUMN_A = TABLE_B.FKCOLUMN_B
AND TABLE_A.COLUMN_A LIKE '%SEARCH%' AND TABLE_B.COLUMN_B LIKE '% %'
Can the SQL optimizer recognize that LIKE %% is as good as removing the condition itself?
Wrap an OR around your "B" table, such as:
AND (len(searchString)=0 OR table_b.column_b LIKE "%searchString%" )
This way, if no value for the string, its length would be zero, and the first part of the OR would be evaluated, always come back as true and return that portion of the equation as valid and ignore the other half using the LIKE clause.
You could apply the same for as many linked tables as you need.
First thing, you have a space in your example:
AND TABLE_B.COLUMN_B LIKE '% %'
That will never be optimized as it is indeed a significant condition.
Now, I think that if it is optimized away depends on the database engine and how smart it is.
For example, SQL Server 2005 does offer the same execution plan for the two types of queries, while MySQL 5.0.38 does not.
LIKE is used with the WHERE clause to search, update, and delete a record using wild cards.
Example:
To search all records whose employee name is starred from a character, 'a':
select * from Employee where Name like 'a%'
To update all records with name amit whose employee name is starting with a character, 'a':
update Employee set Name='amit' where Name like 'a%'
To delete all records whose employee name is starting with a character, 'a':
delete from Employee where Name like 'a%'
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column
LIKE '%[p-s]' -- "It search data from table parameter where sentence ending with p,q,r,s word."
LIKE '[0-9]' --It use for search only numeric value
LIKE '%table%' -- it use for search parameter from table where use "table" keyword'.
LIKE %[^p-r] -- it set the condition where Not Ending With a Range of Characters
Example:
SELECT T1.BrandName,T1.BrandID,T2.CategoryName,T2.Color FROM TABLE1 T1
LEFT JOIN TABLE2 T2 on T1.ID = T2.BrandID
WHERE T1.BrandName LIKE '%Samsung%'
Example:
SELECT T1.BrandName,T1.BrandID,T2.CategoryName,T2.Color FROM TABLE1 T1
LEFT JOIN TABLE2 T2 on T1.ID = T2.BrandID
WHERE T1.BrandName LIKE '%[a-j]'
In MySQL you can also use ILIKE, and then it's case insensitive.
You can rewrite you query like this:
SELECT TABLE_A.* FROM TABLE_A, TABLE_B WHERE TABLE_A.KEYCOLUMN_A = TABLE_B.FKCOLUMN_B
AND (#paramA='' or TABLE_A.COLUMN_A LIKE '%' + #paramA + '%')
AND (#paramB='' or TABLE_B.COLUMN_B LIKE '%' + #paramB + '%')
This way, if paramA or paramB is '', then the other column that is queried inside same parentheses will not be queried.
Use UNION and proper JOINs.
The %foo% search term is bad enough (can't use index) without adding OR and LEN to the mix too.
SELECT
TABLE_A.*
FROM
TABLE_A
JOIN
TABLE_B On TABLE_A.KEYCOLUMN_A = TABLE_B.FKCOLUMN_B
WHERE
TABLE_A.COLUMN_A LIKE '%SEARCH%' AND TABLE_B.COLUMN_B LIKE '%SEARCH2%'
UNION
SELECT
TABLE_A.*
FROM
TABLE_A
WHERE
TABLE_A.COLUMN_A LIKE '%SEARCH%'

Resources