Incorrect syntax near insert [duplicate] - sql

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Incorrect syntax near insert
For some reason I can't get the tables populated. It worked before but I don't know why it won't run now.
CREATE DATABASE Mort;
Go
USE Mort;
-----------------------------------
/*
**This script creates the
** Employee table with the foreign key
*/
-----------------------------------
----------------------------------------------------
/* I chose Job_title as the PRIMARY KEY.
**All rows must be unique. There is a Job_title
**column in the Employee table that can be used as a
**foreign key.
*/
/*
**This script creates the
** Job title table
*/
----------------------------------------------------
CREATE TABLE
Job_title
(Job_title varchar (50) PRIMARY KEY,
EEO_1_Classification varchar(200),
Job_description varchar(250),
Exempt_Non_Exempt_Status bit );
Go
CREATE TABLE
Employee
(Emp_id int NOT NULL IDENTITY(1,1)PRIMARY KEY,
Last_name varchar(25),
First_name varchar(25),
Address varchar(40),
City varchar (15),
State char(2),
Telephone_area_code varchar(3),
Telephone_number varchar(8),
Job_title varchar(50) foreign key references job_title(job_title),
Hire_date smalldatetime,
Wage money,
Gender char(1),
Race varchar(25),
Age int );
-----------------------------------------------------------------------------------------------------
/* (3.1) This script inserts employee records
** for both the administrative offices
** and the Del Mar location
*/
-------------------------------------------------------------------------------------------------
USE Mort;
Go
INSERT INTO
Employee
(Last_name,
First_name,
Address,
City,
State,
Telephone_area_code,
Telephone_number,
Job_title,
Hire_date,
Wage,
Gender,
Race,
Age)
VALUES
('McNamara',
'Juanita',
'923 Parkway',
'La Jolla',
'CA',
'619',
'555-0208',
'Accounting Clerk',
'10/07/2003',
'$12.75',
'F',
'Hispanic',
32);
INSERT INTO
Employee
(Last_name,
First_name,
Address,
City,
State,
Telephone_area_code,
Telephone_number,
Job_title,
Hire_date,
Wage,
Gender,
Race,
Age)
VALUES
('Stephens',
'Harvey',
'7863 High Bluff Drive',
'La Jolla',
'CA',
'619',
'555-0123',
'Dir. of Fin.
& Acct.',
'3/1/1998',
'$75,000.00',
'M',
'Caucasian',
51);
INSERT INTO
Employee
(Last_name,
First_name,
Address,
City,
State,
Telephone_area_code,
Telephone_number,
Job_title,
Hire_date,
Wage,
Gender,
Race,
Age)
VALUES
('Vu',
'Matthew',
'981 Torrey Pines Road',
'La Jolla',
'CA',
'619',
'555-0138',
'Computer Support Specialist',
'8/16/2000',
'$18.50',
'M',
'Asian',
26);
INSERT INTO
Employee
(Last_name,
First_name,
Address,
City,
State,
Telephone_area_code,
Telephone_number,
Job_title,
Hire_date,
Wage,
Gender,
Race,
Age)
VALUES
('Nguyen',
'Meredith',
'10583 Arenas ST. ',
'La Jolla ',
'CA',
'619',
'555-0102',
'Computer Support Specialist ',
'9/27/1998 ',
'$21.50 ',
'M',
'Caucasian',
25);
INSERT INTO
Employee
(Last_name,
First_name,
Address,
City,
State,
Telephone_area_code,
Telephone_number,
Job_title,
Hire_date,
Wage,
Gender,
Race,
Age)
VALUES
('Avery',
'Ledonna',
'198 Governor Dr.',
'Del Mar',
'CA',
'619',
'555-0135',
'Asst. - Bakery & Pastry',
'3/28/2003',
'$10.50',
'F',
'African American',
23);
INSERT INTO
Employee
(Last_name,
First_name,
Address,
City,
State,
Telephone_area_code,
Telephone_number,
Job_title,
Hire_date,
Wage,
Gender,
Race,
Age)
INSERT INTO
Employee
(Last_name,
First_name,
Address,
City,
State,
Telephone_area_code,
Telephone_number,
Job_title,
Hire_date,
Wage,
Gender,
Race,
Age)
VALUES
('Drohos',
'Craig',
' ',
'Selano Beach',
'CA',
'619',
'555-0202',
'Assistant Manager',
'6/15/2000',
'$51,000.00 ',
'M',
'Caucasian',
32);
INSERT INTO
Employee
(Last_name,
First_name,
Address,
City,
State,
Telephone_area_code,
Telephone_number,
Job_title,
Hire_date,
Wage,
Gender,
Race,
Age)
VALUES
('Meier',
'Elaine',
'9703 Orchid Lane',
'Del Mar',
'CA',
'858',
'555-0112',
'Cashier',
'9/10/2000',
'$10.25',
'F',
'Asian',
51);
INSERT INTO
Employee
(Last_name,
First_name,
Address,
City,
State,
Telephone_area_code,
Telephone_number,
Job_title,
Hire_date,
Wage,
Gender,
Race,
Age)
VALUES
('Quillian',
'Stanley',
'98542 Wandering Road Apt 2-B',
'Del Mar',
'CA',
'760',
'555-0198',
'Asst. - Butchers & Seafood Specialists',
'12/16/1999',
'$11.50 ',
'M',
'American Indian',
29);
INSERT INTO
Employee
(Last_name,
First_name,
Address,
City,
State,
Telephone_area_code,
Telephone_number,
Job_title,
Hire_date,
Wage,
Gender,
Race,
Age)
VALUES
('Tyink',
'Thomas',
'87592 Pacific Heights Blvd.',
'Del Mar',
'CA',
'858',
'555-0159',
'Asst. - Bakery & Pastry',
'5/1/2001',
'$9.50',
'M',
'African American',
32);
INSERT INTO
Employee
(Last_name,
First_name,
Address,
City,
State,
Telephone_area_code,
Telephone_number,
Job_title,
Hire_date,
Wage,
Gender,
Race,
Age)
VALUES
('Vance',
'Brent',
'927 Cynthia Lane Parkway',
'Del Mar',
'CA',
'858',
'555-0147',
'Bagger - 30 hours/wk',
'3/29/2001',
'$6.75',
'M',
'Caucasian',
22);
------------------------------------------------------
/* This script inserts values into Job_title table
** Note: 1 means exempt (salaried)
** 0 means non-exempt (hourly)
** Section (2.2)
*/
------------------------------------------------------
INSERT INTO Job_title
(Job_title, EEO_1_Classification, Job_description, Exempt_Non_Exempt_Status )
VALUES
('Accounting Clerk', 'Office/Clerical',
'Computes, classifies, records, and verifies numerical data for use in maintaining
accounting records.',
0);
INSERT INTO Job_title
(Job_title, EEO_1_Classification, Job_description, Exempt_Non_Exempt_Status )
VALUES
('Assistant Manager', 'Officials & Managers',
'Supervises and coordinates activities of workers in department of food store.
Assists store manager in daily operations of store.' ,
1);
INSERT INTO Job_title
(Job_title, EEO_1_Classification, Job_description, Exempt_Non_Exempt_Status )
VALUES
('Bagger','Sales Workers',
'Places customer orders in bags. Performs carryout duties for customers.',
0);
INSERT INTO Job_title
(Job_title, EEO_1_Classification, Job_description, Exempt_Non_Exempt_Status )
VALUES
('Cashier','Sales Workers',
'Operates cash register to itemize and total customer’s purchases in grocery
store.',
0);
INSERT INTO Job_title
(Job_title, EEO_1_Classification, Job_description, Exempt_Non_Exempt_Status )
VALUES
('Computer Support Specialist','Technician',
'Installs, modifies, and makes minor repairs to personal computer hardware and
software systems, and provides technical assistance and training to system
users.',
0);
INSERT INTO Job_title
(Job_title, EEO_1_Classification, Job_description, Exempt_Non_Exempt_Status )
VALUES
('Dir. of Fin. & Acct.','Officials & Managers',
'Plans and directs the finance and accounting activities for Kudler Fine Foods.',
1);
INSERT INTO Job_title
(Job_title, EEO_1_Classification, Job_description, Exempt_Non_Exempt_Status )
VALUES
('Asst. - Bakery & Pastry','Craft Workers (Skilled)',
'Obtains or prepares food items requested by customers in retail food store.',
0);
INSERT INTO Job_title
(Job_title, EEO_1_Classification, Job_description, Exempt_Non_Exempt_Status )
VALUES
('Asst. - Butchers & Seafood Specialists','Operatives (Semi skilled)',
'Obtains or prepares food items requested by customers in retail food store.',
0);
INSERT INTO Job_title
(Job_title, EEO_1_Classification, Job_description, Exempt_Non_Exempt_Status )
VALUES
('Stocker','Office/Clerical',
'Stores, prices and restocks merchandise displays in store.',
0)
------------------------------------------------------------------------------------------
/*
**(3.2) This script Checks the results by selecting
**all of the columns from both of the tables
**Select * from
**Select * from
*/
/*
**Format of Employee table due to requirement
**Do not “string out” an entire query/statement so
**that it requires the viewer to horizontally scroll to read it.
*/
-------------------------------------------------------------------------------------------
USE Mort;
Select Emp_id, Last_name, First_name, Address, City, State from Employee
Go
Select Telephone_area_code, Telephone_number, Job_title, Hire_date, Wage, Gender, Race, Age from Employee
Go
Select * from Job_title
Go
/*
**(3.3) Write a SQL query that joins two tables in the example database and uses BETWEEN **to restrict record selection. (Use salary to restrict the data.)
*/
Select Employee.Wage, Job_title.Job_title
From Employee
inner join Job_title
on Employee.Wage=Job_title.Job_title
order by Employee.Last_name
(3.4) Write a SQL query that joins two tables in the example database and uses BETWEEN to restrict record selection. (Use hire dates to restrict the data.)
(3.5) Write a SQL query that joins two tables in the example database and uses LIKE to restrict record selection. (Use telephone area codes to restrict data.)
(3.6) Write a SQL query that joins two tables in the example database and uses LIKE to restrict record selection. (Use age to find all people in their 20’s.)
(3.7) Write a SQL query that uses UNION of the two tables. Be creative.
(3.8) Write a SQL query that displays the average salary / hourly wage grouped by job_title.
(3.9) Write a SQL query that displays the number of people in each EE0-1 Classification and the average salary / hourly wage for each classification.
(3.10) Group employees by EEO classification: Select the employees’ last names and group them by EEO-1 Classification
(3.11) Group employees by salary within their EEO classification: Select the employees’ last names and group them by salary within their EEO-1 Classification.
(3.12) Select the employees’ last names and group them by salary within job titles that are grouped into exempt and non-exempt.

You don't have a VALUES section for one of the INSERT's(the 6th INSERT)

Related

Using if-then or case-when-then to select from dataset

I have a dataset with students in 1st, 2nd and 3rd grades. I want to select the names of all students in 1st and 2nd grades, but only students named John, Jane or Smith from 3rd grade. Here is what I have so far:
select
first_name,
grade_level
from table_with_all_students_info
-- I need an if or case when statement here saying if student is in third grade, their first name selected can only be John, Jane or Smith. My attempt is below.
case when grade_level in ('3rd grade')
then first_name in ('John', 'Jane', 'Smith')
I'm not sure what I'm getting wrong there but I'd appreciate some help. Thanks
You can UNION two queries such as this:
select first_name, grade_level
from table
where grade_level in ('1st','2nd')
union
select first_name, grade_level
from table
where grade_level = '3rd'
and first_name in ('John','Jane','Smith')
Use where with or:
select
first_name,
grade_level
from table_with_all_students_info
where (grade_level = '3rd grade' and first_name in ('John', 'Jane', 'Smith'))
or grade_level in ('1st grade', '2nd grade')
If there are only 3 grades in your data, you can replace grade_level in ('1st grade', '2nd grade') with grade_level != '3rd grade'

Order of Procedure for Select statement with Where Clause and other operators

This is the table I'm working off:
CREATE TABLE Person
(
IdNo number (3),
Name VARCHAR2(30),
Gender VARCHAR2(3),
QtyA number (3),
QtyB number (3),
Primary Key (IdNo)
);
INSERT INTO Person (IdNo, Name, Gender, QtyA, QtyB)
VALUES (23,'Johnny Storm','M',10,10);
INSERT INTO Person (IdNo, Name, Gender, QtyA, QtyB)
VALUES (46,'Eric Twinge ','M',7,4);
INSERT INTO Person (IdNo, Name, Gender, QtyA, QtyB)
VALUES (17,'Diana Prince ','F',4,7);
INSERT INTO Person (IdNo, Name, Gender, QtyA, QtyB)
VALUES (28,'Susan Storm ','F',1,3);
INSERT INTO Person (IdNo, Name, Gender, QtyA, QtyB)
VALUES (134,'Dick Grayson ','m',6,2);
INSERT INTO Person (IdNo, Name, Gender, QtyA, QtyB)
VALUES (5,'Barbara Gordon ','F',8,7);
INSERT INTO Person (IdNo, Name, Gender, QtyA, QtyB)
VALUES (24,'Selina Kyle ','F',4,0);
INSERT INTO Person (IdNo, Name, Gender, QtyA, QtyB)
VALUES (78,'Rick Hunt ','M',NULL,NULL);
INSERT INTO Person (IdNo, Name, Gender, QtyA, QtyB)
VALUES (81,'Ted Howler ','M',6,6);
INSERT INTO Person (IdNo, Name, Gender, QtyA, QtyB)
VALUES (89,'Sonita Marks ','F',3,6);
INSERT INTO Person (IdNo, Name, Gender, QtyA, QtyB)
VALUES (2,'Dave Orkle ','M',2,4);
From this order of procedure that was provided in class:
Parentheses
*/
+-
= <= >= < >
IS
Between
NOT
AND
OR
I have to work out how many rows of the following statement with show up:
SELECT Name FROM person
WHERE gender = 'F' OR gender = 'M'
AND QtyA+QtyB < 5
Is this statement read in this order:
QtyA+QtyB
QtyA+QtyB < 5
gender = 'F'
gender = 'M'
gender = 'M' AND QtyA+QtyB < 5
gender = 'F' OR gender = 'M'
My logic that is probably wrong is:
Since no parentheses it does the addition first - QtyA+QtyB
Then it does < operator as it's the next one on that list given to me < 5.
Then it does the = which is gender = 'F'
Then gender = 'M' as it's the next equal
Then it does the AND operator so gender = 'M' AND QtyA+QtyB
Finally it does the OR operator then gender = 'F' OR gender = 'M'
So 0 rows will show up after step 5
The next test apparently has a large section where you have to read Select statements and find how many rows will show from them without typing anything in and I feel like I'm doing this completely wrong, but I came up with 0 which is what the select statement gave me when I type it in.
You want to apply parentheses. The query as written is expressing:
WHERE (gender = 'F') OR
(gender = 'M' AND (QtyA + QtyB) < 5)
That is because AND has higher precedence than OR. Then arithmetic operations are going to be evaluated before comparisons.

Get records from table with join where records in join not contain specific value

I have two tables:
Table user:
create table user (
id bigserial not null primary key,
username varchar(256),
active boolean not null default true
);
And table address:
create table address (
id bigserial not null primary key,
user_id integer not null,
country varchar(256),
city varchar(256),
street varchar(256)
);
And some data as example:
insert into user(id, username, active) values (1, 'john', true);
insert into user(id, username, active) values (2, 'alex', true);
insert into user(id, username, active) values (3, 'alice', true);
insert into user(id, username, active) values (4, 'tom', true);
insert into user(id, username, active) values (5, 'dave', true);
insert into address(id, user_id, country, city, street) values (1, 1, 'Germany', 'Berlin', '');
insert into address(id, user_id, country, city, street) values (2, 2, 'Germany', 'Berlin', '');
insert into address(id, user_id, country, city, street) values (3, 2, 'Great Britain', 'London', '');
insert into address(id, user_id, country, city, street) values (4, 3, 'France', 'Paris', '');
insert into address(id, user_id, country, city, street) values (5, 4, 'USA', 'New York', '');
insert into address(id, user_id, country, city, street) values (6, 5, 'South Korea', 'Seoul', '');
Every user can have several addresses. I need to get all users who doesn't have in their set of addresses address with specific country, for example 'Germany'.
What I tried:
select u.* from user u
left join address a on u.id=a.user_id where a.country is not like '%Germany%'
But it returns users, who have address with specific country but also have some other address, which country is different from the specific one, for example with the data used above this is alex, who has two addresses Germany and Great Britain:
id username active
--------------------
2 alex True
3 alice True
4 tom True
5 dave True
Any suggestions how can I do such query?
Your code checks whether each user has at least one address outside of Germany, while you want to ensure that they have none.
I would recommend not exists:
select c.*
from client c
where not exists (
select 1
from address a
where a.user_id = c.id and a.country = 'Germany'
)
This query would take advantage of an index on address(user_id, country).
Note that it is unclear whether your table is called user or client... I used the latter.
Note that this also returns clients that have no address at all. If that's not what you want, then an alternative uses aggregation:
select c.*
from client c
inner join address on a.user_id = c.id
group by c.id
having not bool_or(a.country = 'Germany')
This is the query:
select user_id from address where country = 'Germany'
that returns all the users that you want to filter out.
Use it with NOT IN:
select u.*
from user u
where id not in (select user_id from address where country = 'Germany')
See the demo.
Results:
> id | username | active
> -: | :------- | :-----
> 3 | alice | t
> 4 | tom | t
> 5 | dave | t

Inserting values into tables Oracle SQL

I'm trying to insert values into an 'Employee' table in Oracle SQL. I have a question regarding inputting values determined by a foreign key:
My employees have 3 attributes that are determined by foreign keys: State, Position, & Manager. I am using an INSERT INTO statement to insert the values and manually typing in the data. Do I need to physically look up each reference to input the data or is there a command that I can use? E.g.
INSERT INTO Employee
(emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
VALUES
(001, "John Doe", "1 River Walk, Green Street", 3, 5, 1000)
This should populate the employee table with (John Doe, 1 River Walk, Green Street, New York, Sales Executive, Barry Green). New York is state_id=3 in the State table; Sales executive is position_id=5 in the positions table; and Barry Green is manager_id=1000 in the manager table.
Is there a way in which I can input the text values of the referenced tables, so that Oracle will recognise the text and match it with the relevant ID? I hope this question makes sense will be happy to clarify anything.
Thanks!
You can expend the following function in order to pull out more parameters from the DB before the insert:
--
-- insert_employee (Function)
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2)
RETURN VARCHAR2 AS
p_state_id varchar2(30) := '';
BEGIN
select state_id
into p_state_id
from states where lower(emp_state) = state_name;
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES
(p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);
return 'SUCCESS';
EXCEPTION
WHEN others THEN
RETURN 'FAIL';
END;
/
INSERT
INTO Employee
(emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT '001', 'John Doe', '1 River Walk, Green Street', state_id, position_id, manager_id
FROM dual
JOIN state s
ON s.state_name = 'New York'
JOIN positions p
ON p.position_name = 'Sales Executive'
JOIN manager m
ON m.manager_name = 'Barry Green'
Note that but a single spelling mistake (or an extra space) will result in a non-match and nothing will be inserted.
You can insert into a table from a SELECT.
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
(SELECT id FROM state WHERE name = 'New York'),
(SELECT id FROM positions WHERE name = 'Sales Executive'),
(SELECT id FROM manager WHERE name = 'Barry Green')
FROM
dual
Or, similarly...
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
state.id,
positions.id,
manager.id
FROM
state
CROSS JOIN
positions
CROSS JOIN
manager
WHERE
state.name = 'New York'
AND positions.name = 'Sales Executive'
AND manager.name = 'Barry Green'
Though this one does assume that all the look-ups exist. If, for example, there is no position name 'Sales Executive', nothing would get inserted with this version.

SQL Server 2005 Full Text Search over multiple tables and columns

I'm looking for a good solution to use the containstable feature of the SQL Serve r2005 effectivly. Currently I have, e.g. an Employee and an Address table.
-Employee
Id
Name
-Address
Id
Street
City
EmployeeId
Now the user can enter search terms in only one textbox and I want this terms to be split and search with an "AND" operator. FREETEXTTABLE seems to work with "OR" automatically.
Now lets say the user entered "John Hamburg". This means he wants to find John in Hamburg.
So this is "John AND Hamburg".
So the following will contain no results since CONTAINSTABLE checks every column for "John AND Hamburg".
So my question is: What is the best way to perform a fulltext search with AND operators across multiple columns/tables?
SELECT *
FROM Employee emp
INNER JOIN
CONTAINSTABLE(Employee, *, '(JOHN AND Hamburg)', 1000) AS keyTblSp
ON sp.ServiceProviderId = keyTblSp.[KEY]
LEFT OUTER JOIN [Address] addr ON addr.EmployeeId = emp.EmployeeId
UNION ALL
SELECT *
FROM Employee emp
LEFT OUTER JOIN [Address] addr ON addr.EmployeeId = emp.EmployeeId
INNER JOIN
CONTAINSTABLE([Address], *, '(JOHN AND Hamburg)', 1000) AS keyTblAddr
ON addr.AddressId = keyTblAddr.[KEY]
...
This is more of a syntax problem. How do you divine the user's intent with just one input box?
Are they looking for "John Hamburg" the person?
Are they looking for "John Hamburg Street"?
Are they looking for "John" who lives on "Hamburg Street" in Springfield?
Are they looking for "John" who lives in the city of "Hamburg"?
Without knowing the user's intent, the best you can hope for is to OR the terms, and take the highest ranking hits.
Otherwise, you need to program in a ton of logic, depending on the number of words passed in:
2 words:
Search Employee data for term 1, Search Employee data for term 2, Search Address data for term 1, Search address data for term 2. Merge results by term, order by most hits.
3 words:
Search Employee data for term 1, Search Employee data for term 2, Search employee data for term 3, Search Address data for term 1, Search address data for term 2, Search address data for term 3. Merge results by term, order by most hits.
etc...
I guess I would redesign the GUI to separate the input into Name and Address, at a minimum. If that is not possible, enforce a syntax rule to the effect "First words will be considered a name until a comma appears, any words after that will be considered addresses"
EDIT:
Your best bet is still OR the terms, and take the highest ranking hits. Here's an example of that, and an example why this is not ideal without some pre-processing of the input to divine the user's intent:
insert into Employee (id, [name]) values (1, 'John Hamburg')
insert into Employee (id, [name]) values (2, 'John Smith')
insert into Employee (id, [name]) values (3, 'Bob Hamburg')
insert into Employee (id, [name]) values (4, 'Bob Smith')
insert into Employee (id, [name]) values (5, 'John Doe')
insert into Address (id, street, city, employeeid) values (1, 'Main St.', 'Springville', 1)
insert into Address (id, street, city, employeeid) values (2, 'Hamburg St.', 'Springville', 2)
insert into Address (id, street, city, employeeid) values (3, 'St. John Ave.', 'Springville', 3)
insert into Address (id, street, city, employeeid) values (4, '5th Ave.', 'Hamburg', 4)
insert into Address (id, street, city, employeeid) values (5, 'Oak Lane', 'Hamburg', 5)
Now since we don't know what keywords will apply to what table, we have to assume they could apply to either table, so we have to OR the terms against each table, UNION the results, Aggregate them, and compute the highest rank.
SELECT Id, [Name], Street, City, SUM([Rank])
FROM
(
SELECT emp.Id, [Name], Street, City, [Rank]
FROM Employee emp
JOIN [Address] addr ON emp.Id = addr.EmployeeId
JOIN CONTAINSTABLE(Employee, *, 'JOHN OR Hamburg') AS keyTblEmp ON emp.Id = keyTblEmp.[KEY]
UNION ALL
SELECT emp.Id, [Name], Street, City, [Rank]
FROM Employee emp
JOIN [Address] addr ON emp.Id = addr.EmployeeId
JOIN CONTAINSTABLE([Address], *, 'JOHN OR Hamburg') AS keyTblAdd ON addr.Id = keyTblAdd.[KEY]
) as tmp
GROUP BY Id, [Name], Street, City
ORDER BY SUM([Rank]) DESC
This is less than ideal, here's what you get for the example (in your case, you would have wanted John Doe from Hamburg to show up first):
Id Name Street City Rank
2 John Smith Hamburg St. Springville 112
3 Bob Hamburg St. John Ave. Springville 112
5 John Doe Oak Lane Hamburg 96
1 John Hamburg Main St. Springville 48
4 Bob Smith 5th Ave. Hamburg 48
But that is the best you can do without parsing the input before submitting it to SQL to make a "best guess" at what the user wants.
I had the same problem. Here is my solution, which worked for my case:
I created a view that returns the columns that I want. I added another extra column which aggregates all the columns I want to search among. So, in this case the view would be like
SELECT emp.*, addr.*, ISNULL(emp.Name,'') + ' ' + ISNULL(addr.City, '') AS SearchResult
FROM Employee emp
LEFT OUTER JOIN [Address] addr ON addr.EmployeeId = emp.EmployeeId
After this I created a full-text index on SearchResult column. Then, I search on this column
SELECT *
FROM vEmpAddr ea
INNER JOIN CONTAINSTABLE(vEmpAddr, *, 'John AND Hamburg') a ON ea.ID = a.[Key]