Query Using Tables From 2 Server

Oct 31, 2000

Can anybody tell me how to use the query analyzer to
connect to 2 different servers in one query?
If I access a database on another server like that
[servername].[dbname].[dbo].[tablename] I recieve
an error that says: Server servername is not configured
for DATA ACCESS.

Thanks in advance

Gert

View 2 Replies


ADVERTISEMENT

SQL Server 2012 :: Query To Return Top 10 Tables On Each Database On Server?

Nov 21, 2013

i need a query to return the top 10 tables in each database on a server. have used EXEC sp_msforeachtable 'sp_spaceused ''?''' which returns what I need for one db but I need it to loop through and gather the info for all dbs on server. maybe need cursor not sure. for reporting reasons i would like to include the name of the server and name of database.

View 3 Replies View Related

Query/Reporting Tool For SQL Server Tables

Oct 6, 2005

Just a general question about any recommendations for a third party tool that would allow setting up a data-dictionary against SQL Server tables and a user could go in and build their own queries, reports. Perhaps they could save their query/report definitions for reuse. Other nice to haves - ability to output to PDF and export to XLS. Would prefer web interface, but can consider desktop as well. Any immediate recommendations?

Thanks.

View 6 Replies View Related

Creating Tables In SQL Server Via Query Analyzer With Relationships

Jun 7, 2005

I've been searching around for some info on how to set this up, but with no luck.I need to have a .sql file that will set up a few tables and these tables will have relationships and contraints.I can do this by hand in enterprise manager, but need to set up some procedures that will do the same thing.For instance, I can create the tables just fine.....CREATE TABLE students ( sId int NOT NULL PRIMARY KEY,        studentId varchar(50) NOT NULL,               course varchar(50)              )
CREATE TABLE courses  ( cId int NOT NULL PRIMARY KEY,        course varchar(50) NOT NULL,               sco varchar(50)              )But, I need to set up relationships in there somehow.Once student may have many courses (one to many) and one course may have many sco's (one to many) SCO would be another table.Can someone point me to a good link that would show how to complete these procedures?Thanks all,Zath

View 4 Replies View Related

SQL Server 2012 :: How To Combine Data From Different Tables Using A Query

Dec 17, 2013

I have a set of tables that look like what I have shown below. How I can achieve the desired output ?

CREATE TABLE #ABC([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductA INT);
CREATE TABLE #DEF([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductB INT);
CREATE TABLE #GHI([Year] INT, [Month] INT,Customer Varchar(10), SalesofProductC INT);

INSERT #ABC VALUES (2013,1,'PPP',1);
INSERT #ABC VALUES (2013,1,'QQQ',2);
INSERT #ABC VALUES (2013,2,'PPP',3);

[Code] ....

I have a query currently that looks like this . @Month and @Year are supplied as parameters

SELECT
-- select the sum for each year/month combination using a correlated subquery (each result from the main query causes another data retrieval operation to be run)
(SELECT SUM(SalesofProductA) FROM #ABC WHERE [Year]=T.[Year] AND [Month]=T.[Month]) AS [Sum_SalesofProductA]

[Code] ...

Right now I see an output like this : for a particular value of @Month and @Year

SalesofProductA, SalesofProductB, SalesofProductC What I would like to see is :

[Customer],SalesofProductA, SalesofProductB, SalesofProductC

How it can be done ?

View 2 Replies View Related

SQL Server 2012 :: Query To Consolidate Data From Tables

Feb 12, 2014

I need to make a query that counts installed developer software for all our developers (from the sccm database), for licensing purposes. The trick here is that a license should only be counted once per. developer and that should be the highest version. But in the database, the developers can have different versions of the software installed (upgrades) on the same computer and they often use several computers with different software versions.

So for example: A source table with two developers

-------------------------------------------------------------------
| dev1 | comp1 | Microsoft Visual Studio Ultimate 2013
| dev1 | comp1 | Microsoft Visual Studio Professional 2010
| dev1 | comp2 | Microsoft Visual Studio Premium 2010
| dev2 | comp3 | Microsoft Visual Studio Professional 2010
| dev2 | comp4 | Microsoft Visual Studio Premium 2012
--------------------------------------------------------------------

I want the result to be:
-----------------------------------------------------
| dev1 | Microsoft Visual Studio Ultimate 2013
| dev2 | Microsoft Visual Studio Premium 2012
------------------------------------------------------

I have created a query using cursors that give me the correct result, but it's way to slow to be acceptable (over 20 min..). I also toyed with the idea of creating some sort of CRL proc or function in C# that does the logic, but a SCCM consultant from MS said that if I create any kind of custom objects on the SCCM SQL Server instance, we loose all support from them. So I'm basically stuck with using good old fashioned T-SQL queries.

My idea now, is to use a CTE table and combine it with a Temp table with the software and a rank. I feel that I'm on the right track, but I just can't nail it properly.

This is how far I have come now:

IF OBJECT_ID('tempdb..#swRank') IS NULL CREATE TABLE #swRank(rankID int NOT NULL UNIQUE, vsVersion nvarchar(255))
INSERT INTO #swRank(rankID, vsVersion)
VALUES
(1, 'Microsoft Visual Studio Ultimate 2013'),
(2, 'Microsoft Visual Studio Ultimate 2012'),

[Code] ....

View 4 Replies View Related

SQL Server 2012 :: Increment Query Based On Two Tables?

Feb 17, 2014

I have two tables with this info:

TABLE 1

COL1 COL2 COL3
AAA BBB CCC
QQQ WWW EEE
AAA SSS DDD
WWW EEE RRR
BBB BBB BBB

TABLE 2

COL1 COL2 COL3 COL4
b b b 343
a a a 344
c c c 345
d d d 346
e e e 347

I want to insert TABLE 1 into TABLE 2 with a query that will auto increment to COL4 looking like this:

COL1 COL2 COL3 COL4
b b b 343
a a a 344
c c c 345
d d d 346
e e e 347
AAA BBB CCC 348
QQQ WWW EEE 349
AAA SSS DDD 350
WWW EEE RRR 351
BBB BBB BBB 352

I know this can be done easily by just altering the column to have an auto-increment datatype, but I currently cannot do that at this moment.

View 5 Replies View Related

SQL Server 2008 :: Query Joining Multiple Tables Getting Duplicates?

May 17, 2013

I'm joining several tables and when I add the last one I get duplicate results. How can I get just one for each?

select a.field, b.field, c.field
from atblname as a inner join btblname as b on a.id = b.parent_id
left outer join ctblname as c on a.id = c.parent_id

There are more than one result when joining tbl a and c, but I'm getting a reult for each of them for all results from joining a and b.

View 9 Replies View Related

SQL Server 2014 :: Query To Combine Two Tables Based Third Table

Feb 18, 2015

I have three tables A, B, C respectively. Table C is used to map table A and B. Three tables are below:

Table A:

Table B:

Table C:

So what query do I need write to have table like below?

Table D

View 7 Replies View Related

SQL Server 2008 :: Turning Complex Query Into Temp Tables

Mar 5, 2015

do you have a general rule of thumb for breaking a complex query into temp tables? For someone who is not a sql specialist, a query with more than a few table joins can be complex. So a query with 10+ table joins can be overwhelming for someone who is not a sql specialist.

One strategy is to break a problem into pieces so to speak by grouping together closely related tables into temp tables and then joining those temp tables together. This simplifies complex SQL and although not as performant as one big query it's much easier to understand. So do you have a general rule of thumb as far as a threshold for the number of joins you include in a query before you break the query into temp tables?

View 9 Replies View Related

SQL Server 2012 :: How To Perform Update Query That Involves Multiple Tables

Aug 31, 2015

I am trying to run an update statement against a vendor's database that houses HR information. If I run a regular select statement against the database with the following query, it returns without error:

SELECT "QUDDAT_DATA"."QUDDAT-INT", "NAME"."INTERNET-ADDRESS", "QUDDAT_DATA"."QUDFLD-FIELD-ID", "QUDDAT_DATA"."QUDTBL-TABLE-ID"
FROM "SKYWARD"."PUB"."NAME" "NAME", "SKYWARD"."PUB"."QUDDAT-DATA" "QUDDAT_DATA"
WHERE ("NAME"."NAME-ID"="QUDDAT_DATA"."QUDDAT-SRC-ID") AND "QUDDAT_DATA"."QUDTBL-TABLE-ID"=0 AND "QUDDAT_DATA"."QUDFLD-FIELD-ID"=16 AND "QUDDAT_DATA"."QUDDAT-INT"=11237When I try to convert it into an

[Code] ....

I am assuming I am receiving this error because it doesn't know where to find QUDDAT-INT? How can I fix that?

The "QUDDAT-INT" column houses the employee number. So in the case of the SELECT query above, I am testing against a specific employee number.

View 9 Replies View Related

SQL Server 2014 :: Query For Listing Views In A Database Involving Tables From Other Databases?

Oct 19, 2015

script to get the list of views in a database, involving tables from other databases?I AM using SQL server 2014

View 2 Replies View Related

Linked Server Oracle Tables - Not Able To Add To Query Designers Show Diagram Pane Via Add Table Dialogue

Apr 18, 2008

I am new to sqlserver.


1)I created a linked server to a oracle database, works fine. Now I am writing queries, using "Query Desgner", when I do a "Add table" linked server tables do not appear. Is this a limitation. I can get around the problem by creating a view.

2) When I use "Microsoft OLE DB Provider for Oracle" for linked server, some times connection seems to get lost. On one occassion, the next day it was fine, it re-established itself.

Any ideas thnx.

View 5 Replies View Related

Query Server To Find All Partitioned Tables, Partition Name, Column Used, Partitioned By

Dec 17, 2007

I want to find a way to get partition info for all the tables in all the databases for a server. Showing database name, table name, schema name, partition by (maybe; year, month, day, number, alpha), column used in partition, current active partition, last partition (for date partitions I want to know if the partition goes untill 2007, so I can add 2008)

all I've come up with so far is:






Code Block

SELECT distinct o.name From sys.partitions p
inner join sys.objects o on (o.object_id = p.object_id)
where o.type_desc = 'USER_TABLE'
and p.partition_number > 1

View 3 Replies View Related

Query View Vs Query Tables Directly

May 19, 2008

Greetings,

I recently started working with a database that uses several views, none of which are indexed. I've compared the execution plans of querying against the view versus querying against the tables and as best I can tell from my limited knowledge the two seem to perform equally. It seems to me that having the view is just one more thing I need to keep track of.

I've done some google searches but haven't found anything that really tells me which performs better, querying the view or the tables directly. Generally speaking which is better?

Thanks in advance for your replies.

View 3 Replies View Related

SQL 2012 :: Extract All Tables Names And Their Row Counts From Linked Server Tables

Oct 7, 2015

I am using the following select statement to get the row count from SQL linked server table.

SELECT Count(*) FROM OPENQUERY (CMSPROD, 'Select * From MHDLIB.MHSERV0P')

MHDLIB is the library name in IBM DB2 database. The above query gives me only the row count of table MHSERV0P. However, I need to get the names, rowcounts, and sizes of all tables that exist in MHDLIB librray. Is it possible at all?

View 1 Replies View Related

Exporting Data From Excel Tables To SQL Server Tables

Dec 9, 2007

Hi all,
 I have a large Excel file with one large table which contains data, i've built a SQL Server DataBase and i want to fill it with the data from the excel file.
 
How can it be done?
 
 
Thanks, Michael.

View 1 Replies View Related

Insert Records From Foxpro Tables To SQL Server Tables

Apr 22, 2004

Hi,

Currently, I'm using the following steps to migrate millions of records from Foxpro tables to SQL Server tables:

1. Transfer Foxpro records to .dat files and then bcp to SQL Server tables in a dummy database. All the SQL tables have the same columns as the Foxpro tables.
2. Manipulate the data in the SQL tables of the dummy database and save the manipulated data into the SQL tables of the real database where the tables may have different structure from the corresponding Foxpro tables.

I only know the following ways to import Foxpro data into SQL Server:

#1. Transfer Foxpro records to .dat files and then bcp to SQL Server tables
#2. Transfer Foxpro records to .dat files and then Bulk Insert to SQL Server tables
#3. DTS Foxpro records directly to SQL Server tables

I'm thinking whether the following choices will be better than the current way:

1st choice: Change step 1 to use #2 instead of #1
2nd choice: Change step 1 to use #3 instead of #1
3rd choice: Use #3 plus manipulating in DTS to replace step 1 and step 2

Thank you for any suggestion.

View 2 Replies View Related

SQL Server 2008 :: Query To Select Date Range From Two Tables With Same Date Range

Apr 6, 2015

I have 2 tables, one is table A which stores Resources Assign to work for a certain period. The structure is as below

Name StartDate EndDate
Tan 2015-04-01 08:30:00.000 2015-04-01 16:30:00.000
Max 2015-04-01 08:30:00.000 2015-04-01 16:30:00.000
Alan 2015-04-01 16:30:00.000 2015-04-02 00:30:00.000

The table B stores the item process time. The structure is as below

Item ProcessStartDate ProcessEndDate
V 2015-04-01 09:30:10.000 2015-04-01 09:34:45.000
Q 2015-04-01 10:39:01.000 2015-04-01 10:41:11.000
W 2015-04-01 11:44:00.000 2015-04-01 11:46:25.000
A 2015-04-01 16:40:10.000 2015-04-01 16:42:45.000
B 2015-04-01 16:43:01.000 2015-04-01 16:45:11.000
C 2015-04-01 16:47:00.000 2015-04-01 16:49:25.000

I need to select the item which process in 2015-04-01 16:40:00 and 2015-04-01 17:30:00. Beside that I need to know how many resource is assigned to process the item in that period of time. I only has the start date is 2015-04-01 16:40:00 and end date is 2015-04-01 17:30:00. How I can select the data from both tables. There is no need for JOIN, just seperate selections.

Another item process time is in 2015-04-01 10:00:00 and 2015-04-04 11:50:59.

The result expected is

Table A

Name StartDate EndDate
Alan 2015-04-01 16:30:00.000 2015-04-02 00:30:00.000

Table B

Item ProcessStartDate ProcessEndDate
A 2015-04-01 16:30:10.000 2015-04-01 16:32:45.000
B 2015-04-01 16:33:01.000 2015-04-01 16:35:11.000
C 2015-04-01 16:37:00.000 2015-04-02 16:39:25.000

Scenario 2 expected result

Table A

Name StartDate EndDate
Tan 2015-04-01 08:30:00.000 2015-04-01 16:30:00.000
Max 2015-04-01 08:30:00.000 2015-04-01 16:30:00.000

Table B

Item ProcessStartDate ProcessEndDate
Q 2015-04-01 10:39:01.000 2015-04-01 10:41:11.000
W 2015-04-01 11:44:00.000 2015-04-01 11:46:25.000

View 8 Replies View Related

Query Two Tables

Jun 25, 2007

hi,I have two tables,   t1                    t2col1                 col1    col2 1                      1          0 2                      1          0 3                      1          1 4                      2          0 5                      2          0 6                      3          1 7                      3          1 8                      4          1 9                      4          1 10                    4          1 11                    4          1t2.col1 is the key from t1.col1I want to retrieve all t1.col1 records which equal to t2.col1 and tb2.col2 has ONLY "1"the result should be: 3, 4I try:select tb1.col1 from t1 as tb1 where tb1.col1 in (select col1 from t2 where col1=tb1.col1 and col2=1 and ...???.)any help?

View 8 Replies View Related

Query On 2 Tables

Feb 16, 2005

Hello all,
If I write this query :SELECT [Client].[CLI_NAME], [Client].[CLI_PRENOM] FROM Client, Commandes the return is good.

But If I the query is :SELECT [Client].[CLI_NOM] & " " & [Commandes].[CMD_DATE_ORDER] As Ordered FROM Client, Commandes I have an error "Invalid column name.

The CLI_NOM field is on Client Table and CMD_DATE_ORDER is on the other Order table.
How to make a good query with an aliased column without error ?

Thanks for reply.
Regards.
PAB.

View 4 Replies View Related

2 Tables, 1 Query

Aug 25, 2005

I have two tables: 1 with data, the other 3 columns from the first table with rows filled with data that needs to be ommitted when a query is made on the first table.

For example, say I have a column named "meat" and there are rows in it with "beef" as the data. In the other table there is also a column with meat and beef as the data. I would need to query both tables to first get the data to be ommitted and then use that result to query the first table. I hope I'm making sense, any help would be appreciated

View 2 Replies View Related

Query Three Tables - Please Help

Jul 31, 2007

Hi

I need to be able pull certain data from our database. I need to find all stockitems (itemid column) that are a T item (binname column) and the memo to be created before the 01/02/2007 (timeanddatecreated column)

To get the data I need - I need to query three tables.

Stockitem - This has the column "itemid"
Stockitemmemo - This has the column "itemid" and "timeanddatecreated"
Binitem - This has the column "itemid" and "binname"

My results must be based on the following criteria......

All the itemid's have a 'T' in binitem.binname and the memo must have been created before 01/02/2007.

I do have two questions based on the above....

1. Does it make sense what I need?
2. Is it possible

:confused:

Any help would be gratefully received.

Thanks

Simba

View 6 Replies View Related

Tables Used By Query

Oct 25, 2012

I want to get the list of tables which an SQL query is using. It could be through some query or parser written in jruby or R or any other language,any thrd party tool(freeware)or any scripts.

View 1 Replies View Related

Query From 3 Tables

Jun 5, 2008

Hi,
I know it is simple query but I am confused.
I need to make a query from 3 tables in the same database. There are no relations between these tables.
Here is result I need.
KE LE JE
15 775.5 398
18 192.23 399


Please help me.


Sep

View 4 Replies View Related

Query Two Tables

Sep 15, 2014

I'm doing a query from two tables. the table "pr" and the table "prre" with the following data: pr.no, pr.nome, pr.data, pr.recibo, pr.ettsuj, pr.ettdesc, prre.cr pr.eliquido, prre.rqtt , prre.ervu, prre.ere

I'm doing the following query:

select cast(pr.no as varchar) as 'Numero',pr.nome as 'Nome',pr.data as 'Data',cast(pr.recibo as varchar) as 'Recibo',
cast(prre.rqtt as integer) as 'Qt Dias', prre.ervu as 'valor unitario',prre.ere as 'Total Subsidio',
pr.ettsuj as 'Total iliquido', pr.ettdesc as 'Total Descontos', pr.eliquido as 'Total Liquido'
from pr
inner join prre on prre.prstamp=pr.prstamp

for this query is a list of salaries, with the fields, official number, expiration, name, date, receipt number, net total, the total gross, days subsidy amount, subsisidio.

View 7 Replies View Related

Max - Query From Two Tables

Mar 5, 2015

I've got a problem with my query : [URL] ....

I want to say:

Pull all users whos status is New and they have at least one Completed delivery

The problem is, I am getting multiple delivery records form one patient, but I would like to see only newest one. So instead of this result:

2014-05-10 00:00:00.000CompletedReed BrewerNew830
2014-06-10 00:00:00.000CompletedReed BrewerNew830
2014-07-10 00:00:00.000CompletedReed BrewerNew830
2014-07-02 00:00:00.000CompletedColton DukeNew920

I would like to get this:

2014-07-10 00:00:00.000CompletedReed BrewerNew830
2014-07-02 00:00:00.000CompletedColton DukeNew920

I have tried to use Max , but it does not work ....

select
Max(delivery.deliveryDate),
delivery.deliveryStatus,
patient.userName,
patient.userStatus,
delivery.accountid

[Code] ....

View 1 Replies View Related

Query 2 Tables

Mar 15, 2007

I all,

i have a problem with a query.

I have two tables (Software and Licenses), and one software can have one or more licenses.

So what i want to get from this query is:

- all info of the software table
- and, if the software have or not, attributed licenses.

How can i do that?

View 11 Replies View Related

Two Tables Query

Jul 13, 2007

hi,

i have two tables generally:

bB_posts
- postid
- title
- body
- posttime
- commentcount
bB_comments
- commentid
- postid (FK)
- commenttext
*/

Select t1.title, t1.body, t1.posttime, t2.commenttext

from bB_posts as t1
join bB_comments as t2
on t2.postid = t1.postid
(or t1.commentcount = 0)


This query prints out all the posts which have 1 or more complementary comments. But i would aslo like to print the posts which have 0 comments (seen in brackets).

how should i do this?

thank you

View 6 Replies View Related

Query On 2 Tables

Aug 22, 2007

Hi guys,

i have 2 tables in a database. Table A contains:
State City Employee_firstEmployee_LastAge
KarnatakaBangaloreDavid Na 23
KarnatakaBangalorePrakash Na 25
KarnatakaMysore Naina Na 26
KarnatakaMysore David Na 35
MaharashtraMumbai Parneet Na 24
MaharashtraMumbai Vikas Na 33
MaharashtraPune Amit Na 25
MaharashtraPune Amit Na 19

Table B contains:

State Employee_firstEmployee_LastSalary
KarnatakaDavid Reinjal 15556
KarnatakaPrakash Mehra 15323
KarnatakaDavid Petre 36524
KarnatakaKumar Mehra 56123
MaharashtraParneet Kaur 23315
MaharashtraVikas Pandey 35645
MaharashtraAmit D'Souza 23564
MaharashtraAmit Dhogla 12354


The output should be:

State CityEmployee_firstEmployee_LastAgeSalary
Karnataka BangaloreDavid Reinjal 2315556
Karnataka MysoreDavid Mehra 3556123
Karnataka MysoreNaina Petre 2636524
Karnataka BangalorePrakash Mehra 2515323
Maharashtra MumbaiParneet Kaur 2423315
Maharashtra MumbaiVikas Pandey 3335645
Maharashtra PuneAmit D'Souza 2523564
Maharashtra PuneAmit Dhogla 1912354


I tried using Inner join but it gave me a all together different output. how can i do using Union? Can anybody help me with this?

Regards,

David Reinjal

View 6 Replies View Related

Query For Tables.

Mar 2, 2007

how can i fetch somw rows having same field value?

my table is like:

name id

x 1

y 2

z 2

w 5

so how can i get rows y and z for id=id ?

View 3 Replies View Related

Sql Query To Search In Two Tables

Jun 25, 2007

 i have two tables,
Opportunity

[OpporID] [numeric](18, 0) IDENTITY (1000, 1) NOT NULL ,
[OpportunityID] [varchar] (16) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[OpportunityTypeID] [numeric](10, 0) NOT NULL ,
[SLABased] [int] NOT NULL ,
[LoginID] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[DateCreated] [datetime] NOT NULL ,
[AccountID] [int] NOT NULL ,
[GeographyID] [int] NOT NULL ,
[VerticalID] [int] NOT NULL ,
[BDMID] [int] NOT NULL ,
[Probability] [int] NOT NULL ,
[PASStatus] [int] NULL ,
[InsertedDate] [datetime] NULL ,
[InsertedBy] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[UpdatedDate] [datetime] NULL ,
[UpdatedBy] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[UpdatedFlag] [int] NULL

and SKILL
[SkillNo] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,
[OpportunityID] [numeric](18, 0) NOT NULL ,
[OrderId] [numeric](18, 0) NOT NULL ,
[PracticeID] [int] NULL ,
[SkillID] [int] NOT NULL ,
[NoOfPeople] [int] NOT NULL ,
[Clientinterview] [int] NOT NULL ,
[Location] [int] NOT NULL ,
[JDAttached] [int] NOT NULL ,
[JDFilePath] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Status] [int] NULL ,
[Experience] [int] NULL ,
[InsertedDate] [datetime] NULL ,
[InsertedBy] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[UpdatedDate] [datetime] NULL ,
[UpdatedBy] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[UpdatedFlag] [int] NULL ,
[GeoLocation] [int] NULL
)

i want to make a stored procedure for custom search on these two tables
with the following fields given to the user as an option to make his
choice..
from opportunity table -
OpportunityTypeID,SLABased,AccountID ,
GeographyID,
VerticalID,
BDMID,
Probability

and from skill table
SkillID, Location, GeoLocation

and return all the fields of opportunity table.

Can some make the stored procedure for me..

thanks a lot.

View 3 Replies View Related

Query Using Multiple Tables

Feb 11, 2005

Hi, I have a problem which I thought it has a simple solution but now I'm not even sure it is possible.

I have 3 tables Clients <-oo ClientContacts oo-> Contacts
(the <-oo means one to may relation between the tables)

A Client may have related none, one or many Contact records. The table ClientContacts is the link that stores that information. The field ClientContacts.Category represents the type of the contact and it will be used in queries. It may be owner, accountant, employee, etc.

My goal is to run a query which will return

Clients.Company, Clients.MailingStreet, Clients.MailingCity, Clients.MailingState
Contacts.FirstName, Contacts.LastName, Contacts.[E-mailAddress]
WHERE (Clients.WorkOnHold = 0)

The result should return values for
Contacts.FirstName, Contacts.LastName, Contacts.[E-mailAddress] if the Client has attached Contact records filtered by category,
and '','','' or <NULL>,<NULL>,<NULL> if the Client does not have any Contact records.


I tryed an INNER JOIN but it will return juts the records having contact information.

Any solutions are appreciated.
Thanks.



Clients

CREATE TABLE [Clients] (
[ClientID] [int] IDENTITY (1, 1) NOT NULL ,
[Company] [varchar] (100),
[MailingStreet] [varchar] (50),
[MailingCity] [varchar] (35),
[MailingState] [varchar] (35) ,
[MailingZip] [varchar] (10),
[WorkOnHold] [bit] NULL ,
[ClientNotes] [varchar] (500),
CONSTRAINT [PK_Clients] PRIMARY KEY CLUSTERED
(
[ClientID]
) ON [PRIMARY]
) ON [PRIMARY]
GO


Contacts

CREATE TABLE [Contacts] (
[ContactID] [int] IDENTITY (1, 1) NOT NULL ,
[FirstName] [varchar] (50) NOT NULL ,
[LastName] [varchar] (50) NOT NULL ,
[JobTitle] [varchar] (50),
[BusinessStreet] [varchar] (50),
[BusinessCity] [varchar] (35),
[BusinessState] [varchar] (35),
[BusinessPhone] [varchar] (20),
[BusinessFax] [varchar] (20),
[E-mailAddress] [varchar] (255),
CONSTRAINT [PK_Contacts] PRIMARY KEY CLUSTERED
(
[ContactID]
) ON [PRIMARY]
) ON [PRIMARY]
GO


ClientContacts

CREATE TABLE [ClientContacts] (
[ClientID] [int] NOT NULL ,
[ContactID] [int] NOT NULL ,
[Category] [varchar] (50),
CONSTRAINT [FK_ClientContacts_Clients] FOREIGN KEY
(
[ClientID]
) REFERENCES [Clients] (
[ClientID]
) ON DELETE CASCADE ,
CONSTRAINT [FK_ClientContacts_Contacts] FOREIGN KEY
(
[ContactID]
) REFERENCES [Contacts] (
[ContactID]
) ON DELETE CASCADE
) ON [PRIMARY]
GO


The INNER JOIN I tryed but is not good. It returns just clients having contacts attached.

SELECT Clients.Company, Clients.MailingStreet, Clients.MailingCity, Clients.MailingState, Contacts.FirstName, Contacts.LastName,
Contacts.[E-mailAddress]
FROM ClientContacts INNER JOIN
Clients ON ClientContacts.ClientID = Clients.ClientID INNER JOIN
Contacts ON ClientContacts.ContactID = Contacts.ContactID
WHERE (Clients.WorkOnHold = 0)

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved