Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Where IN this and IN that

Author  Topic 

Dobly
Starting Member

16 Posts

Posted - 2010-09-02 : 18:47:15
OH, this one is doing my head in.

I am doing query that will tell if if a User has Access to a Location via the Territory each is in. Sounds simple enough but here's the details.

A Location can be in one or many Territories.
A User can be assigned to one or many Territories.

The tables look like this.

Location
LocationID (PK)

LocationTerritory
LocationID (FK)
TerritoryID (FK)

Territory
TerritoryID (PK)

UserTerritory
UserID (FK)
TerritoryID (FK)

User
UserID

So if a Location is in Territories 3, 4 and 5
and a user is assigned to Territories 5, 6 and 7
That would match as Territory 5 is common to both.

If the user is assigned to Territories 6, 7 and 8, no match would be made.

I should add that a user might not be assigned to any Territories. Likewise a Location might not be in any Territories.

This might be really simple but at the moment I just can't see it.



tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-09-02 : 18:52:49
Wouldn't you just use an INNER JOIN for this?

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

Dobly
Starting Member

16 Posts

Posted - 2010-09-02 : 18:56:58
quote:
Originally posted by tkizer

Wouldn't you just use an INNER JOIN for this?

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog



No.. I cracked it. It was simple after all.

SELECT Location_ID
FROM LocationTerritory
WHERE Location_ID = @LocationID
AND Territory_ID IN (SELECT Territory_ID from UserTerritory WHERE User_ID = @UserID)


Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-09-03 : 00:39:03
I'd still use a JOIN:

SELECT lt.Location_ID
FROM LocationTerritory lt
JOIN UserTerritory ut
ON lt.Territory_ID = ut.Territory_ID
WHERE lt.Location_ID = @LocationID AND ut.User_ID = @UserID

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -