Join In A View - Simple Question

Jan 19, 1999

I've got a simple ( I think) question on views. I've got a view that has a table join in it.
With this view, we want to be able to perform updates, inserts, and deletes. At this time
we can do the updates and inserts, but not deletes. I've checked the permissions and
the users have SELECT, INSERT, UPDATE, and DELETE. Am I missing something or are
deletes just not possible in a view with a join?

CREATE VIEW update_bd_view
AS select
D.BD_ID, D.BD_DESC, T.BT_TYPE_TID, T.BT_TYPE_FID, T.BT_JOB_FID
FROM BILLING_DESC D JOIN BILLING_TIME T ON D.BD_ID=T.BT_ID
GO

thank you for your time!
Toni Eibner

View 1 Replies


ADVERTISEMENT

Simple Join Not So Simple

Feb 21, 2007

I am receiving funny results from a query. To simplify, I have 2 tables (todayyesterday). Each tbl has the same 8 columns. My query joins the two tables then looks where either of two columns has changed. What is happening is that when checking one of the columns it seems as though sql is flipping the column, causing it to be returned in error.

result set

colA colB colC colD colE colF colG colG (from yesterday)
1 1 a b c d e m
1 1 a b c d m e

So what's happening is that the record above is actually the same record and should not be returned. There is a daily pmt column that changes but I am not using that in the query. Aside from that the two records are identicle.

Any help is appreciated.

View 7 Replies View Related

Simple Join Not So Simple

Aug 19, 2006

Hi,

I have the following situation (with a site that already works and i cannot modify the database architecture and following CrossRef tables -- you will see what i mean by CrossRef tables below)

I have:


Master table Hotel

table AddressCrossRef (with: RefID = Hotel.ID, RefType = 'Hotel', AddrID)
joins
table Address (key = AddrID)


table MediaCrossRef (with RefID = Hotel.ID, RefType= 'Hotel', MediaID)
joins
table Media (with MediaID,mediaType = 'thumbnail')


foreach hotel, there definitely is a crossRef entry in AddressCrossRef and Address tables respectively (since every hotel has an address)

however not all hotels have thumbnail image

hence i have hotel inner join AddressXReff inner join Address ..... however i must have
left outer join mediaXref left outer join media


the problem is that if there is no entry in Media or mediaXref, I don't get any results

i tried to get over it by using
where (media.mediaTyple like 'thumbnail' or media.mediaType is null)
but then i started getting multiple results for each hotel because media's of type movie or full_image or etc... all got returned


any clue?

thanks

View 5 Replies View Related

Help With Simple Join?

Sep 3, 2004

I don't know if it's Friday or what, but I can't for the life of me come up with an easy way to do this:

I have 3 tables I want to join:

Sale Table:
Sale_No Cus_No Sale_Qty
1 Joe01 250

Order Table:
Ord_No Sale_No Order_Qty ShipToCode
1 1 20 DestA
2 1 20 DestA
3 1 20 DestA
4 1 20 DestB
5 1 20 DestB

ShipTo Table:

Cus_No ShipToCode ShipToName
Joe01 DestA Philadelphia
Joe01 DestB Chicago
Bob01 DestA Boston


A sale for say 100 tons would have 5 orders (each for 20 tons) associated with it by Sale_No. Each of those orders can go to a different ShipTo destination. Since only the ShipTo Code is stored in the Orders table, I need to get the ShipToName. However, As demonstrated in the example table above, the key in the ShipTo table is both Cus_No AND ShipToCode.

I want a list of Sales and Orders, which is an inner join on Sale_No, piece of cake. However, I then need to use the ShipTo table to go from the ShipToCode to the ShipToName. Unfortunately, Cus_No is not in the Orders table, it is back in the Sales table (proper normalization is a pain sometimes).

What I came up with is this, but is this correct?:


FROM Sales INNER JOIN
Orders ON Sales.sale_no = Orders.sale_no INNER JOIN
ShipTo ON Orders.ShipToCode = ShipTo.ShipToCode AND
Sales.cus_no = ShipTo.cus_no

View 12 Replies View Related

Problem With A View (not A Simple One)

Jan 19, 2007

Hi,

I have a table that is something like this:

Products ----------------- idProduct as int, idPart1 as int, idPart2 as int, idPart3 as int

then other table, which is something like:

Parts: ---------------------- idPart as int, partName as VarChar(30)

Now, some products only take one part, but others will take as many as 3 parts. Since it's a relatively small number I thought it would be better to put 3 different idParts on the product table and have two of them allow nulls, instead of creating a Master / Detail kind of thing. My question is, how do I create a view with something like:

v_Products ----------------- idProduct as int, namePart1 as VarChar(30), namePart2 as VarChar(30), namePart3 as VarChar(30)

I'm using SQL Server 2005 (Express Edition, but the SQL is the same so...). I'm using this code:

SELECT dbo.products.idProduct, dbo.parts1.partName, dbo.parts2.partName, dbo.parts3.partName FROM dbo.products INNER JOIN dbo.parts AS parts1 ON dbo.products.idPart1=parts1.idPart INNER JOIN(...)

Help? :s

View 4 Replies View Related

JOIN Simple Problem

Sep 20, 2005

Hi Guys,

I have the following table called VMailMessages:


PHP Code:




 MessageNum  MailboxNum  State
========================
1                 100             1
2                 101             1
3                 101             1
4                 102             0 






Which is of messages in a mailbox system, the MessageNum is my primary key, MailboxNum indicates which mailbox it is for and State indicates whether it is 'New' (value = 1) or 'Saved' (value = 0).

What I want to do is write a query to obtain a list of mailboxes, along with how many New and how many Saved messages they have, producing a result table like this:


PHP Code:




 MailboxNum  NewCount  SavedCount
===========================
100             1             0
101             2             0
102             0             1 






My problem is I cannot seem to get my SQL right, so far I've got:


PHP Code:




 SELECT NewQuery.MailboxNum, NewQuery.NewCount, SavedQuery.SavedCount 
FROM (SELECT MailboxNum, COUNT(1) AS NewCount
          FROM VMailMessages
          WHERE (State = '1')
          GROUP BY MailboxNum) NewQuery 
FULL OUTER JOIN
         (SELECT MailboxNum, COUNT(1) AS SavedCount
           FROM VMailMessages
           WHERE (State = '0')
           GROUP BY MailboxNum) SavedQuery 
ON NewQuery.MailboxNum = SavedQuery.MailboxNum 






WHich works only if the mailbox has New messages as well as Saved messages. For mailboxes with only Saved messages, the count appears but, the MailboxNum is NULL. The opposite occurs if I change my SELECT clause to ask for SavedQuery.MailboxNum, but I really want both.

Can anyone help me?

Thanks

Richard

View 1 Replies View Related

Simple JOIN Question

Mar 28, 2007

I feel like this is an easy question, but I can't describe it well enough to find the answer I need by searching. Anyway, in my spare time (I'm definitely not a SQL Query pro) I'm putting together a small app for our local Little League to help with scheduling.

I have 2 tables I need to join:

T1 = Schedule
has the following fields:
ID
hTeamID (ID of Home team)
vTeamID (ID of Vistor team)
Time
Date

T2 = Teams
ID
Name
Other info...

I want to be able to do a SELECT statement on the schedule table and JOIN the team names for both home and visitor. I've tried a bunch of different ways but keep getting errors. I can think of 100's of reasons to join the same table more than once, but I still don't know how to and can't find the answer online.

Thanks in advance.

View 2 Replies View Related

T-SQL (SS2K8) :: Simple Self Join

Aug 6, 2014

I have listed two tables table 1 has some data. I have to update table 2 [reports] column from table 1 [reports] using self join..I should get as table 2 after updating

View 1 Replies View Related

Best Way To Do A Simple Join Query

Feb 28, 2007

ive seen so many ways to do this, including some using cursors (strange i know)

but i have tableA and tableB i want to show fields from tableA which don't apear in tableB

what is the MOST efficient way to do this

View 2 Replies View Related

Read Only Cells In A Simple View

Feb 12, 2007

Mikel Arzak writes "Hi,

I have a DB migrated from SQL Server 2000 to SQL Server 2005 and I
have a strange problem that I don't find any reason.

I make a simple SQL Query with one table showing all the fields and
everything goes well. But when I insert another auxiliar table and
showing one field, then I can't change any field of the main table.
SQL Server shows me the message Read Only Cell. Why this happens? This problem didn't happen in SQL Server 2000.

The select sentence that works:

SELECT Notas_Estructura.* FROM Notas_Estructura

The previous Select sentence modified that doesn't work:

SELECT Notas_Estructura.*, Alumnos.Apellido1, Alumnos.Apellido2,
Alumnos.Nombre FROM Notas_Estructura INNER JOIN Alumnos ON Notas_Estructura.CodAlumno = Alumnos.CodAlumno

Thanks for your help."

View 1 Replies View Related

Simple Query, INNER Join Problem

Sep 14, 2006

In a single table I have 2 columns. Date | Number2006/09/01 - 2352006/09/03   - 2452009/08/01 - 230 I want to write a query that will return the AVG number between two dates.  I am assuming this will require a JOIN but I'm having problems implementing my solution.  I think about it, it's probably not a join but a sub query...I was trying the following: SELECT Date, AVG(Number) as AVERAGE_NUMBER
FROM test.Table
WHERE ( Date>='09/01/2006' AND DATE<='09/04/2006' )  But I keep getting date is invalid in the select list because it is not contained in either an aggregate funtion or a group by clause.  Thanks in advance for your help. 

View 2 Replies View Related

Simple Question Regarding Outer Join (was SQL Help)

Sep 4, 2006

Hi Everyone,

I have a simple question regarding outer join.

Please see the attached word file. It has screen shots of the query I am running. My first query shows the result where i have M.ReservationID = MA.MeetingID and it counts NoofRSVP (# of times the query runs). I have to modify first query in such a way that it returns records from eCDReservations table even if there is no matching MeetingID in MeetingAttendees table (means Null, see the result of 2nd query in attached file). So in my result for that case NoofRSVP column should show either Null or 0.

View 3 Replies View Related

Simple Outer Join Question

May 31, 2007

Ok here is the situation. I have 2 tables.

Movies
MovieID Title Year
21 A Beautiful Mind 2002
22 Forrest Gump 1994
23 The English Patient 1999


Actors
ActorID MovieID Name
1 22 Tom Hanks
2 21 Russell Crowe
3 23 Ralph Fiennes
4 NULL Nachiket Mehta

Here is the SQL Query.

SELECT ActorID, Name, Title, Year FROM Actors LEFT OUTER JOIN Movies ON Actors.MovieID = Movies.MovieID

Now, I only want to show movies made in 1990's and display all 4 actors. If I put

WHERE Year < 2000

it won't show the fourth actor because he doesn't have any movies. I need to show all 4 actors here and NULL for movies if they don't have any.

Hope this makes sense. Thank you.



Nachiket

View 3 Replies View Related

Simple JOIN, INTERSECT Query

Apr 25, 2006

Hi,We are in the process of buying a new server to run mssql. Howeverbefore this as a tempory fix to using a msaccess backend i believethrough odbc i need to address the following issue:SELECT ai.entry_date as CallTime,ai.agent_login as AgentsLogin,ai.campaign as MarketingCampaign,ai.agent_input2 as ProductsSold,ai.first_name as Cust_FirstName,ai.last_name as Cust_LastName,ai.agent_input1 as Cust_PersonalNumber,ai.street_address as Cust_AddressStreet,ai.city as Cust_AddressCity,ai.state as Cust_AddressState,ai.zip as Cust_AddressZIP,rec.file_name as AgreementRecordingFileFROM agent_input ai, leads l, recordings recWHERE ai.whole_phone_number = l.whole_phone_number ANDl.call_status = 1110 ANDrec.whole_phone_number = l.whole_phone_number ANDrec.last_name = l.last_name ANDrec.agent = ai.agent_login ANDrec.campaign = l.campaign ANDlast_call_date between #04/24/2006 12:00 AM# and #04/25/2006 11:59 PM#ORDER BY ai.agent_login, ai.entry_dateI want to make the recordings entry optional so the same results comeout whether it matches a recording or not. If it does i want it topopulate the AgreementRecordingFile column above, if not just put a ''as you would with '' as AgreementRecordFile.Does anyone know how you can do this, in a access based database systemusing SQL through i believe ODBC?ThanksDavid

View 1 Replies View Related

Simple OUTER JOIN (I Thought)

Sep 11, 2007

Two tables:FruitfruitID, fruitNameBasketbuyerID, fruitID(ie. we can see which buyer has what fruit in their basket)I simply want to display all available fruit and whether or not it'sin a specific persons' basket.SELECT Fruit.fruitID, Fruit.fruitName, IsNull(buyerID, 0)FROM Fruit INNER JOIN Basket ON Fruit.fruitID = Basket.fruitIDWHERE Basket.buyerID = 12but this just gives me what's in buyer 12s' basket.What am I doing wrong? Am I a basket case...

View 2 Replies View Related

Strange Result From A Simple JOIN

Sep 18, 2007



I am currently studying Transact SQL and playing around with queries from a sample database. Recently I created the following query.


USE MemtrackSQL

SELECT m1.MemberID, m1.Surname, m1.FirstName, m1.DateOfBirth

FROM tblMember m1 JOIN tblMember m2

ON m1.FirstName = m2.FirstName

WHERE m1.MemberID <> m2.MemberID


This simple query is designed to show all members with the same first name as other members. The result I got shows duplicates of existing members an inconsistent number of times even though I specified not to show duplicates with WHERE m1.MemberID <> m2.MemberID


2 Scharenguivil Rodney 1958-06-24 00:00:00.000
2 Scharenguivil Rodney 1958-06-24 00:00:00.000
2 Scharenguivil Rodney 1958-06-24 00:00:00.000
5 O'Grady Patrick 1975-09-23 00:00:00.000
7 Greenfield Lynne 1955-07-26 00:00:00.000
8 Harvy Simon 1965-08-27 00:00:00.000
8 Harvy Simon 1965-08-27 00:00:00.000
8 Harvy Simon 1965-08-27 00:00:00.000
8 Harvy Simon 1965-08-27 00:00:00.000


Any help in explaining where I have gone wrong here would be greatly appreciated.

Cheers

View 3 Replies View Related

Error With A Simple JOIN Query....

Apr 12, 2007

Hi!



I've a big problem by using the following query :






Code Snippet

public SqlCeResultSet selectRSQuery(String query)

{

SqlCeResultSet resultSet = initializeCommand(query).ExecuteResultSet(ResultSetOptions.Scrollable | ResultSetOptions.Updatable);

return resultSet;

}



SqlCeResultSet resultSet = sgb.selectRSQuery(

"SELECT p.pId, p.pLogin FROM Profiles p, ProfilesGroups pg, Groups g " +

"WHERE g.gId = pg.tpGroupId " +

"AND p.pId = pg.tpProfileId " +

"AND g.gProfileID = '" + app.Settings.Default.id + "'");



It return me this error :

Cannot generate an updatable cursor for the query because there is a non-standard join expression.



What can I do??



Thxx

View 9 Replies View Related

Deceptively Simple Join / Select Question

Mar 24, 2004

Ok, I have two tables with a child/parent or one -> many relationship:

parent_table:
pid int primary key
pname varchar

child_table:
cid int primary key
pid int
cname varchar

Say the contents of these two tables are:

parent_table:
pid pname:
1 Ben
2 Jesse
3 Michael

child_table
pid cid cname
1 1 ben_Child1
1 2 ben_Child2
1 3 ben_Child3
2 4 jesse_Child1
2 5 jesse_Child2
2 6 jesse_Child3
3 7 michael_Child1
3 8 michael_Child2
3 9 michael_Child3

Now what I would like to be able to do is:

select pname, cname
from
parent table a,
child_table b
where a.pid = b.pid

Except! Instead of getting the results in the form of:

Ben ben_Child1
Ben ben_Child2
Ben ben_Child3
...

I would like them in

Ben ben_Child1 ben_Child2

Now normally this would be impossible (I think) since the query would return an unknown number of columns. But in this case I only care about the FIRST TWO children for each parent. So I'm sure there's some way to do this with a simple select, but I don't know how. Anyone?

View 6 Replies View Related

Simple Group By And Count With Join Not Matching Between Sql Server And Sql CE

Apr 2, 2007

In Sql Server




Code Snippet

CREATE TABLE t_contact

(

Id uniqueidentifier,

FirstName nvarchar(50),

LastName nvarchar(50),

TaskId uniqueidentifier

)

GO

CREATE TABLE t_task

(

Id uniqueidentifier,

Start datetime

)

GO



INSERT INTO t_task (Start, Id) VALUES ('3/25/2007 12:00:00 AM', '5949b899-3230-4d30-b210-9903015b2c6b')

INSERT INTO t_contact (FirstName, LastName, TaskId, Id) VALUES ('Adam', 'Tybor', '5949b899-3230-4d30-b210-9903015b2c6b', '304fc653-d366-404b-878d-9903015b2c6f');

INSERT INTO t_task (Start, Id) VALUES ('4/1/2007 12:00:00 AM', '4bd2df60-ca6c-493d-8824-9903015b2c6f')

INSERT INTO t_contact (FirstName, LastName, TaskId, Id) VALUES ('John', 'Doe', '4bd2df60-ca6c-493d-8824-9903015b2c6f', '7b91f7d6-d71e-47b4-a7ec-9903015b2c6f')

INSERT INTO t_task (Start, Id) VALUES ('3/29/2007 12:00:00 AM', '05167e74-cf63-452a-8f25-9903015b2c6f')

INSERT INTO t_contact (FirstName, LastName, TaskId, Id) VALUES ('Jane', 'Doe', '05167e74-cf63-452a-8f25-9903015b2c6f', '6871ee8d-bc83-478c-8a7c-9903015b2c6f')

GO

SELECT task1_.Start as y0_, count(this_.FirstName) as y1_ FROM t_contact this_ inner join t_task task1_ on this_.TaskId=task1_.Id GROUP BY task1_.Start

GO





Result (Expected)

2007-03-25 00:00:00.000 1
2007-03-29 00:00:00.000 1
2007-04-01 00:00:00.000 1



Result In Sql CE (UnExpected)

2007-03-25 00:00:00.000 3
2007-03-29 00:00:00.000 3
2007-04-01 00:00:00.000 3



Can SQL CE not count with a join? Seems like this a bug with aggregates or joins. I tried everything to try and get the correct result but no luck.



Thanks Adam

View 3 Replies View Related

Inner Join With A View

Oct 20, 2006

anyone know how to inner join with a view?

View 1 Replies View Related

View Behaviour In Join

Jul 20, 2005

Hi Everybody,I have a complex view, that includes a "group by" clause. I'm tryingto join this view with a table, in a very simple query.The problem is that the optimizer is not using the table data as inputfor the view (I expect this because I have arguments for the table,but not for the view), but executing the view in a different step andthen joining to the table by a merge/hash join. This is obviously veryslow.I tried to force nested loops by using hints but it still doesn't usethe table data as input.Has anybody ever seen this?Thanks in advance...

View 3 Replies View Related

Replace View By Join

May 23, 2007

Hi all,

I have a list of Clients like:
Table_Client




ID
Name

10
Bill

11
Frank

12
Carl

13
Rita

14
Jan

15
Bonny

16
Bart

17
George

18
Ann


Now I want to ad some variable data to each client, so I have created a second table like:

Table_Client_Data



ID
ClientID
FieldName
FieldDataString
FieldDataInt
FieldDataDate
FieldDateBoolean

2
10
CustomerNr
g146




4
11
CustomerNr
g121




5
12
CustomerNr
g147




6
13
CustomerNr
g236




7
15
CustomerNr
g245




9
10
Dog



yes

10
11
Dog



No

10
12
Dog



yes

10
13
Dog



No

10
15
Dog



yes

Now I want to have the next table as result in one query:



ID
Name
CustomerNr
Dog

10
Bill
g146
yes

11
Frank
g121
No

12
Carl
g147
yes

13
Rita
g236
No

14
Jan



15
Bonny
g245
yes

16
Bart



17
George



18
Ann




First I have made a VIEW to create, I had used a inner Join

SELECT Table_Client.ID,
Table_Client_Data.FieldDataString AS CustomerNr,
Table_Client_Data_1.FieldDataString AS Dog

FROM Table_Client_Data

INNER JOIN
Table_Client_Data ON Table_Client.ID = Table_Client_Data.ClientID
INNER JOIN
Table_Client_Data as Table_Client_Data_1 ON Table_Client.ID = Table_Client_Data_1.ClientID

WHERE (Table_Client_Data.FieldName = 'CustomerNr') AND (Table_Client_Data_1.FieldName = 'Dog')

View_CliuentData



ID
CustomerNr
Dog

10
g146
yes

11
g121
No

12
g147
yes

13
g236
No

15
g245
yes

Now I join View_CliuentData with Table_Client and I have the right result.

Now my question,
Is there any way to skip the View an do this all in a join. I have tried several things but ... no result.

Tks Bart



View 5 Replies View Related

Cross Join/? Query In A View Help

Feb 4, 2004

Hey All...
Got a View question.
Have 2 tables:
#1 Currencies
|CCY_Name|CCY_Code|

#2 Rates
|CCY1|CCY2|CCY3|...etc|Active|
-> where the Columns CCY# = the Records in #1

How do I build a View to Select the ONE record in #2 where Active=Y, having the CCY_Name from #1 based on #2.CCY1 (Column NAME) = #1.CCY_Code (Record).

Thanks

robbied111

View 2 Replies View Related

Using Union And Join In A Single View

Aug 8, 2006

I have 3 tables I want to use in a view. Table A has field 1,2,3,4,5and table B has field 1,2,3,4,5. I want to do a union on these. (I havedone so successfully if I stop here) I also want to join table C whichhas field 1,6,7,8,9. I would like to join on field 1 and bring in theother fields. I can join table C to A or B. I can union table A and Bbut I do not know how to both union A and B then join C. Can someoneplease help me? Thanks in advance.

View 7 Replies View Related

SQL 2005 BUG - RIGHT OUTER JOIN On View

Oct 12, 2006

I am having no luck reporting this bug on the feedback link. I type in all information and click "Submit" and it just refreshes the page. So, here it is, I hope someone from MS will post this for me.

The problem appears to be a RIGHT OUTER JOIN on a VIEW causes the query to never return, or return very, very slowly. In 2000 SP4 the query returns in 2 seconds, in 2005 (2153) 64bit, it ran for 42 MINUTES before I killed it.

The is a duplication script to show a problem I have. This script uses the AdventureWorks database to demonstrate the problem. This is script is not the best, but shows the problem.

Please no comments on how to work around the problem. This query is generated by a user using and AdHoc reporting tool. I have NO control over how the user or the tool generates the SQL query.

The word "FAILURE" shows the original query which as far as I can tell never returns. The queries after, are different solutions, if I was able to change the user query, which I am not able to do.


-- Create Test Data Table CustomerListTom and Views

USE AdventureWorks
GO

IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'ViewATom'))
DROP VIEW [ViewATom]

IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'ViewBTom'))
DROP VIEW [ViewBTom]

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'CustomerListTom') AND type in (N'U'))
DROP TABLE CustomerListTom
GO

CREATE TABLE [dbo].[CustomerListTom](
[CustomerID] [varchar](6) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[RegionID] [varchar](3) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[FirstName] [dbo].[Name] NOT NULL,
[LastName] [dbo].[Name] NOT NULL,
[EmailAddress] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[AddressLine] [nvarchar](60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[AddressCity] [nvarchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[AddressState] [nchar](3) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[AddressZip] [nvarchar](15) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[AddressCountry] [dbo].[Name] NOT NULL,
[Phone] [dbo].[Phone] NULL,
[BillAddressLine] [nvarchar](60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[BillAddressCity] [nvarchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[BillAddressState] [nchar](3) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[BillAddressZip] [nvarchar](15) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[BillAddressCountry] [dbo].[Name] NOT NULL,
[BillPhone] [dbo].[Phone] NULL,
[ModifiedDate] [datetime] NOT NULL,
)

INSERT INTO CustomerListTom
SELECT
CustomerID = RIGHT(cu.AccountNumber,6),
RegionID = RIGHT('000'+CAST(cu.TerritoryID AS VARCHAR(3)),3),
FirstName = ct.FirstName,
LastName = ct.LastName,
EmailAddress = ct.EmailAddress,
AddressLine = ad.AddressLine1,
AddressCity = ad.City,
AddressState = sp.StateProvinceCode,
AddressZip = ad.PostalCode,
AddressCountry = sp.[Name],
Phone = ct.Phone,

BillAddressLine = ad.AddressLine1,
BillAddressCity = ad.City,
BillAddressState = sp.StateProvinceCode,
BillAddressZip = ad.PostalCode,
BillAddressCountry = sp.[Name],
BillPhone = ct.Phone,

ModifiedDate = cu.ModifiedDate
--,*
FROM Sales.Customer cu
JOIN Sales.Individual id ON id.CustomerID = cu.CustomerID
JOIN Person.Contact ct ON ct.ContactID = id.ContactID
JOIN Sales.CustomerAddress ca ON cu.CustomerID = ca.CustomerID
JOIN Person.Address ad ON ad.AddressID = ca.AddressID
JOIN Person.StateProvince sp ON sp.StateProvinceID = ad.StateProvinceID


-- Create a big enough set of data for testing
DECLARE @i INT
SET @i = 1
WHILE (@i < 30)
BEGIN
INSERT INTO CustomerListTom
SELECT TOP 15 PERCENT
CustomerID = RIGHT(cu.AccountNumber,6),
RegionID = RIGHT('000'+CAST(cu.TerritoryID+@i AS VARCHAR(3)),3),
FirstName = ct.FirstName,
LastName = ct.LastName,
EmailAddress = ct.EmailAddress,
AddressLine = ad.AddressLine1,
AddressCity = ad.City,
AddressState = sp.StateProvinceCode,
AddressZip = ad.PostalCode,
AddressCountry = sp.[Name],
Phone = ct.Phone,

BillAddressLine = ad.AddressLine1,
BillAddressCity = ad.City,
BillAddressState = sp.StateProvinceCode,
BillAddressZip = ad.PostalCode,
BillAddressCountry = sp.[Name],
BillPhone = ct.Phone,

ModifiedDate = cu.ModifiedDate + CASE WHEN @i > 3 THEN 10 ELSE -25 END + @i

FROM Sales.Customer cu
JOIN Sales.Individual id ON id.CustomerID = cu.CustomerID
JOIN Person.Contact ct ON ct.ContactID = id.ContactID
JOIN Sales.CustomerAddress ca ON cu.CustomerID = ca.CustomerID
JOIN Person.Address ad ON ad.AddressID = ca.AddressID
JOIN Person.StateProvince sp ON sp.StateProvinceID = ad.StateProvinceID

SET @i = @i + 1
END


-- Cleanup - Delete Dups for PK
DELETE FROM CustomerListTom
WHERE CustomerID+RegionID IN (
SELECT CustomerID+RegionID
FROM CustomerListTom cu
GROUP BY CustomerID, RegionID
HAVING COUNT(*) > 1)

ALTER TABLE [CustomerListTom]
ADD CONSTRAINT [PK_CustomerListTom] PRIMARY KEY CLUSTERED
(
[CustomerID] ASC,
[RegionID] ASC
)

GO

-- Create Views
GO
CREATE VIEW ViewATom
AS
SELECT *
FROM CustomerListTom cu
WHERE cu.RegionID = '004'
UNION
SELECT *
FROM CustomerListTom cu
WHERE CustomerID NOT IN
(SELECT CustomerID FROM CustomerListTom c2 WHERE c2.RegionID = '004')
AND (CustomerID + CONVERT(char(8), ModifiedDate, 112) + RegionID IN
(SELECT MAX(CustomerID + CONVERT(char(8), ModifiedDate, 112) + RegionID)
FROM CustomerListTom
GROUP BY CustomerID))

GO
CREATE VIEW ViewBTom
AS
SELECT DISTINCT CustomerID
FROM CustomerListTom
GO

QUERY:

USE AdventureWorks

-- FAILURE
-- This query FAILS to return in over 15 mins, cancelled
SELECT TABLEB.CustomerID,
TABLEC.RegionID,
TABLEC.LastName,
TABLEC.FirstName
FROM ViewATom TABLEA
RIGHT OUTER JOIN ViewBTom TABLEB ON TABLEA.CustomerID = TABLEB.CustomerID
RIGHT OUTER JOIN CustomerListTom TABLEC ON TABLEC.CustomerID = TABLEB.CustomerID
WHERE TABLEB.CustomerID IN
('012870','012997','011000','011001','011002','011003','011004','011005','011006','011007',
'011008','011009','011010','011011','011012','011013','011014','011015','011016','011017',
'011018','011019','011020','011150','011153','011144','017230','017220','017254','017257',
'025338','025333','025338','025397','025389','025424','025483','025485','025682','025673',
'029478','029405','029402','029317','029109','018393'
)

return

-- SOLUTIONS
-- Change WHERE TABLEB to WHERE TABLEA, this query returns in less than 1 second
SELECT TABLEB.CustomerID,
TABLEC.RegionID,
TABLEC.LastName,
TABLEC.FirstName
FROM ViewATom TABLEA
RIGHT OUTER JOIN ViewBTom TABLEB ON TABLEA.CustomerID = TABLEB.CustomerID
RIGHT OUTER JOIN CustomerListTom TABLEC ON TABLEC.CustomerID = TABLEB.CustomerID
WHERE TABLEA.CustomerID IN
('012870','012997','011000','011001','011002','011003','011004','011005','011006','011007',
'011008','011009','011010','011011','011012','011013','011014','011015','011016','011017',
'011018','011019','011020','011150','011153','011144','017230','017220','017254','017257',
'025338','025333','025338','025397','025389','025424','025483','025485','025682','025673',
'029478','029405','029402','029317','029109','018393'
)

return

-- Remove RIGHT OUTER on TABLEB, this Query returns in less than 2 seconds
SELECT TABLEB.CustomerID,
TABLEC.RegionID,
TABLEC.LastName,
TABLEC.FirstName
FROM ViewATom TABLEA
JOIN ViewBTom TABLEB ON TABLEA.CustomerID = TABLEB.CustomerID
RIGHT OUTER JOIN CustomerListTom TABLEC ON TABLEC.CustomerID = TABLEB.CustomerID
WHERE TABLEB.CustomerID IN
('012870','012997','011000','011001','011002','011003','011004','011005','011006','011007',
'011008','011009','011010','011011','011012','011013','011014','011015','011016','011017',
'011018','011019','011020','011150','011153','011144','017230','017220','017254','017257',
'025338','025333','025338','025397','025389','025424','025483','025485','025682','025673',
'029478','029405','029402','029317','029109','018393'
)

return

-- Drop PK and run ORIGINAL query, returns in less than 4 seconds

IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomerListTom]') AND name = N'PK_CustomerListTom')
ALTER TABLE [dbo].[CustomerListTom] DROP CONSTRAINT [PK_CustomerListTom]
GO

SELECT TABLEB.CustomerID,
TABLEC.RegionID,
TABLEC.LastName,
TABLEC.FirstName
FROM ViewATom TABLEA
RIGHT OUTER JOIN ViewBTom TABLEB ON TABLEA.CustomerID = TABLEB.CustomerID
RIGHT OUTER JOIN CustomerListTom TABLEC ON TABLEC.CustomerID = TABLEB.CustomerID
WHERE TABLEB.CustomerID IN
('012870','012997','011000','011001','011002','011003','011004','011005','011006','011007',
'011008','011009','011010','011011','011012','011013','011014','011015','011016','011017',
'011018','011019','011020','011150','011153','011144','017230','017220','017254','017257',
'025338','025333','025338','025397','025389','025424','025483','025485','025682','025673',
'029478','029405','029402','029317','029109','018393'
)

return


-- Create PK with NONCLUSTERED and run ORIGINAL query, returns in less than 1 second

IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[CustomerListTom]') AND name = N'PK_CustomerListTom')
ALTER TABLE [dbo].[CustomerListTom] DROP CONSTRAINT [PK_CustomerListTom]
GO
ALTER TABLE [CustomerListTom]
ADD CONSTRAINT [PK_CustomerListTom] PRIMARY KEY NONCLUSTERED
(
[CustomerID] ASC,
[RegionID] ASC
)
GO

SELECT TABLEB.CustomerID,
TABLEC.RegionID,
TABLEC.LastName,
TABLEC.FirstName
FROM ViewATom TABLEA
RIGHT OUTER JOIN ViewBTom TABLEB ON TABLEA.CustomerID = TABLEB.CustomerID
RIGHT OUTER JOIN CustomerListTom TABLEC ON TABLEC.CustomerID = TABLEB.CustomerID
WHERE TABLEB.CustomerID IN
('012870','012997','011000','011001','011002','011003','011004','011005','011006','011007',
'011008','011009','011010','011011','011012','011013','011014','011015','011016','011017',
'011018','011019','011020','011150','011153','011144','017230','017220','017254','017257',
'025338','025333','025338','025397','025389','025424','025483','025485','025682','025673',
'029478','029405','029402','029317','029109','018393'
)

return

View 5 Replies View Related

Join Stored Procedure And View

Jun 22, 2005

   Hi everybody

View 3 Replies View Related

Self Join Using Instead Of Update Trigger On A View

Jan 11, 2008

Hello all...I'd appreciate any help on this one.

I created a View...the view looks at four seperate tables.

Next, I created an Instead of Update trigger on that view. It works fine...for a regular UPDATE...SET.

However, it throws an error when I try an update and self join based on that view:

Update T1
Set RateUsed = T1.RateUsed
From Taxroll..Taxroll T1 Join
Taxroll..Taxroll T2 on
T1.Asmt = T2.Asmt and
T1.Taxyear = T2.Taxyear
Where T1.Asmt = '123456789012'
And T1.Taxyear = 2007
And T2.RollChgNum = ''
And T1.RollChgNum Like '%X'
And IsNull(T1.RateUsed,'') > ''

Msg 414, Level 16, State 1, Line 2
UPDATE is not allowed because the statement updates view "Taxroll..Taxroll" which participates in a join and has an INSTEAD OF UPDATE trigger.

There are a few caveats:
First, I thought the join issue was in the view itself. I re-created the view using no joins...all subqueries and still get the error. Second, I re-created the Instead of Update Trigger with no joins, and still get the error.

Thanks!

View 1 Replies View Related

Cross Database Join In A Data Source View

Jun 21, 2007

Hi,

Is it possible to do a cross database join in a report services data source view? It doesn't look like it.

If not I was thinking of linking the table into the other database.

TIA,
Darren

View 3 Replies View Related

(SQL 2000) Incorrect Results When Using An Outer Join And A View!

Mar 29, 2008

Hi,
I have a query written in SQL 2000 which returns incorrect result. The query uses left outer join and a view. I read an issue related to this in one of microsoft bug report in this article http://support.microsoft.com/kb/321541.

However, there's a slight difference in the sympton second bullet wherein instead of a expression the query returns a fixed string for one of the column value.

Although the issue mentioned in article seems to be fixed. The later one still seems to be reproducible even with Service Pack 4. However, this issue doesn't appear in SQL Server 2005.

Here's the query to reproduce this error.



Code Snippetcreate table t1 (pk1 int not null,primary key (pk1))
create table t2 (pk1 int not null,label1 varchar(10) not null,primary key (pk1))
go
insert into t1 values (1)
insert into t2 values (2, 'XXXXX')
go
create view V as
select pk1, 'ZZZZ' as label1 from t2
go
select A.pk1 as A_pk1, B.pk1 as B_pk1, B.label1 as B_label1
from t1 as A left outer join V as B on A.pk1 = B.pk1
go

This query is similar to the one mentioned in the article except that in the SELECT clause of CREATE VIEW statement I am passing a fixed value for column "label1".

I just want to confirm that this is an issue and no fix is available for this so far.

Regards,
Naresh Rohra.

View 2 Replies View Related

Created View With Join Query - Unable To Fetch Details

Feb 12, 2014

I created a view with a simple join query

there are 2 rows with orderid as null, i am unable to fetch the details when i give WHERE Condition as

"select orderid from joins where orderid=NULL"

Query :

create view joins as
select A.customerid,A.Companyname,A.Contactname,A.City,B.OrderId from Customers A
left join orders B
on A.Customerid=B.Customerid

View 1 Replies View Related

Speed/efficiency Of View Vs. Common/nested Table Expression In A Join

Mar 2, 2008



i have been trying to determine which is the most efficient, with regards to speed and efficiency, between a view and a common/nested table expression when used in a join.

i have a query which could be represented as index view or a common table expression, which will then be used to join against another table.

the indexed view will use indexes when performing the join. is there a way to make the common table expression faster than an indexed view?

View 2 Replies View Related

Can Any One Tell Me The Difference Between Cross Join, Inner Join And Outer Join In Laymans Language

Apr 30, 2008

Hello

Can any one tell me the difference between Cross Join, inner join and outer join in laymans language

by just taking examples of two tables such as Customers and Customer Addresses


Thank You

View 1 Replies View Related

Simple Simple Linking Tables & Perform Calculation

Mar 22, 2007

found it

View 3 Replies View Related







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