473,569 Members | 2,481 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem joining child data (JOIN, subquery, or something else?)

The problem:
I'm updating a report to be "multi-language" capable. Previously,
any items that had text associated with them were unconditionally
pulling in the English text. The database has always been capable of
storing multiple languages for an item, however.

Desired output:
Given the test data below, I'd like to get the following results

select * from mytestfunc(1)
Item_Id, Condition, QuestionText
1876, NOfKids <= 10, This many children is unlikely.

select * from mytestfunc(2)
CheckID, Condition, QuestionText
1876, NOfKids <= 10, NULL

The current SQL for my UDF:
CREATE FUNCTION Annotated_Check (@Lang_ID int) RETURNS TABLE AS RETURN (
SELECT tblCheck.Item_I D, tblCheck.CheckD escr AS Condition,
tblQuestionText .QuestionText
FROM tblCheck LEFT OUTER JOIN tblQuestionText ON (tblCheck.Item_ ID =
tblQuestionText .Item_ID)
WHERE ((tblQuestionTe xt.LanguageRefe rence = @Lang_ID) OR
(tblQuestionTex t.LanguageRefer ence IS NULL))
)

Test data:

CREATE TABLE [dbo].[tblCheck] (
[Item_ID] [int] NOT NULL ,
[CheckDescr] [text] COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NULL ,
[CreationDate] [datetime] NULL ,
[RevisionDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblCheck] ADD
CONSTRAINT [DF__tblCheck__C reati__0D7A0286] DEFAULT (getdate()) FOR
[CreationDate],
CONSTRAINT [PK_Check] PRIMARY KEY CLUSTERED
(
[Item_ID]
) WITH FILLFACTOR = 90 ON [PRIMARY]
GO

CREATE TABLE [dbo].[tblLanguage] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[Priority] [int] NULL ,
[Name] [varchar] (50) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NOT NULL ,
[Spoken] [bit] NULL ,
[CreationDate] [datetime] NULL ,
[RevisionDate] [datetime] NULL
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblLanguage] WITH NOCHECK ADD
CONSTRAINT [PK_Language] PRIMARY KEY CLUSTERED
(
[ID]
) WITH FILLFACTOR = 90 ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblLanguage] ADD
CONSTRAINT [DF__tblLangua__ Creat__2CF2ADDF] DEFAULT (getdate()) FOR
[CreationDate],
UNIQUE NONCLUSTERED
(
[Priority]
) WITH FILLFACTOR = 90 ON [PRIMARY]
GOCREATE TABLE [dbo].[tblQuestionText] (
[Item_ID] [int] NOT NULL ,
[LanguageReferen ce] [int] NOT NULL ,
[QuestionText] [text] COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NULL ,
[SameAs] [int] NULL ,
[CreationDate] [datetime] NULL ,
[RevisionDate] [datetime] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[tblQuestionText] ADD
CONSTRAINT [DF__tblQuesti__ Creat__76969D2E] DEFAULT (getdate()) FOR
[CreationDate],
CONSTRAINT [PK_QuestionText] PRIMARY KEY CLUSTERED
(
[Item_ID],
[LanguageReferen ce]
) WITH FILLFACTOR = 90 ON [PRIMARY]
GO

INSERT INTO tblCheck (Item_ID, CheckDescr)
VALUES(1876, 'NOfKids <= 10')

INSERT INTO tblLanguage (ID, Priority, Name, Spoken)
VALUES(1,1,'Eng lish', 1)
INSERT INTO tblLanguage (ID, Priority, Name, Spoken)
VALUES(2,2,'Esp anol', 1)

INSERT INTO tblQuestionText (Item_ID, LanguageReferen ce, QuestionText)
VALUES (1876, 1, 'This many children is unlikely.')

Any tips or pointers will be appreciated. Thanks.
Jun 21 '06 #1
2 2057
Beowulf (be************ *****@hotmail.c om) writes:
I'm updating a report to be "multi-language" capable. Previously,
any items that had text associated with them were unconditionally
pulling in the English text. The database has always been capable of
storing multiple languages for an item, however.

Desired output:
Given the test data below, I'd like to get the following results
Thanks for the extensive repro!

Then again, the fix is simple:
CREATE FUNCTION Annotated_Check (@Lang_ID int) RETURNS TABLE AS RETURN (
SELECT tblCheck.Item_I D, tblCheck.CheckD escr AS Condition,
tblQuestionText .QuestionText
FROM tblCheck LEFT OUTER JOIN tblQuestionText ON (tblCheck.Item_ ID =
tblQuestionText .Item_ID)
WHERE ((tblQuestionTe xt.LanguageRefe rence = @Lang_ID) OR
(tblQuestionTex t.LanguageRefer ence IS NULL))
)


Change WHERE to AND and skip last condition on IS NULL:

CREATE FUNCTION mytestfunc (@Lang_ID int) RETURNS TABLE AS RETURN (
SELECT C.Item_ID, C.CheckDescr AS Condition, QT.QuestionText
FROM tblCheck C
LEFT JOIN tblQuestionText QT ON C.Item_ID = QT.Item_ID
AND QT.LanguageRefe rence = @Lang_ID
)

This is a classic error on the left join operator - yes, I did it
too! But once you understand it, it's apparent:

The whole FROM JOIN forms a table which is then filtered by WHERE.
In this case the LEFT JOIN as you had written it, never produced
any rows with NULL in the QuestionText columns, as there was a match
for all. But when you move the condition on language to the ON
clause, you only get a matych if the language is the desired one.

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pro...ads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinf...ons/books.mspx
Jun 21 '06 #2
Erland Sommarskog wrote:
<snip>
CREATE FUNCTION Annotated_Check (@Lang_ID int) RETURNS TABLE AS RETURN (
SELECT tblCheck.Item_I D, tblCheck.CheckD escr AS Condition,
tblQuestionText .QuestionText
FROM tblCheck LEFT OUTER JOIN tblQuestionText ON (tblCheck.Item_ ID =
tblQuestionText .Item_ID)
WHERE ((tblQuestionTe xt.LanguageRefe rence = @Lang_ID) OR
(tblQuestionTex t.LanguageRefer ence IS NULL))
)


Change WHERE to AND and skip last condition on IS NULL:

CREATE FUNCTION mytestfunc (@Lang_ID int) RETURNS TABLE AS RETURN (
SELECT C.Item_ID, C.CheckDescr AS Condition, QT.QuestionText
FROM tblCheck C
LEFT JOIN tblQuestionText QT ON C.Item_ID = QT.Item_ID
AND QT.LanguageRefe rence = @Lang_ID
)

This is a classic error on the left join operator - yes, I did it
too! But once you understand it, it's apparent:

The whole FROM JOIN forms a table which is then filtered by WHERE.
In this case the LEFT JOIN as you had written it, never produced
any rows with NULL in the QuestionText columns, as there was a match
for all. But when you move the condition on language to the ON
clause, you only get a matych if the language is the desired one.


Wow. My assumption was that I was going to have to get into some heavy
duty SQL hackery, but it really is quite simple. This even works
correctly if there actually is Spanish text. I had come up with
something of a workaround that would return NULL for me for other
languages if the only text was English, but it returned multiple records
if there was English and Spanish.

Thanks so much for the reply.
Jun 23 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4387
by: Caroline | last post by:
I seem to always want to do this type of join, but I can never find how to do this. I am trying to join two tables. The parent table will always have one row of data and the child may have 0 to 45 rows of data. I am trying to join the tables in an outer join, so if 0 rows in child it is not affected. But I only want one row returned of the...
15
3606
by: Hemant Shah | last post by:
Folks, We have an SQL statement that was coded in an application many years ago (starting with DB V2 I think). When I upgraded to UDB 8.2, the optimizer does not use optimal path to access the data. It takes about 4 minutes to get the data. In previous versions it was instantaneous. What do I need to do to increase the performance?
8
19578
by: Andrew McNab | last post by:
Hi folks, I have a problem with an MS Access SQL query which is being used in an Access Report, and am wondering if anyone can help. Basically, my query (shown below) gets some records from a couple of tables in my database using INNER JOINS and the WHERE clause to specify the required constraints. However, I also want to read two...
1
4162
by: Andrew McNab | last post by:
Hi folks, I have a problem with an MS Access SQL query which is being used in an Access Report, and am wondering if anyone can help. Basically, my query (shown below) gets some records from a couple of tables in my database using INNER JOINS and the WHERE clause to specify the required constraints. However, I also want to read two...
1
1728
by: whatcondo | last post by:
I am having a great deal of trouble with subqueries in Access. I am trying to write a Payroll application, I have the following tables PayRecords +----+------------+--------+----------+ | Id | Date | Pay | Employee | +----+------------+--------+----------+ | 0 | 19/04/2001 | 123.45 | 1 | | 1 | 19/05/2001 | 123.45 | ...
3
412
by: Marco van de Voort | last post by:
Hi, I'm a relative db newbie, and total SQL server newbie and I garbled up the following query ( :xxx are parameters that are filled in by the app) SELECT PERSON.*, CASE ISNULL(cap.captiveid, 0) WHEN 0 THEN cast(0 AS bit) ELSE cast(1 AS bit) END AS ItemPresent FROM PERSON p
12
3917
by: info | last post by:
The following query works fine in access and does exactly what I want it to do however I get a syntax error when I port it over to SQL Server 2000. ------------- UPDATE OrdersProducts INNER JOIN Products ON OrdersProducts.ProductID = Products.ProductID SET Products.Stock = Products.Stock-OrdersProducts.Quantity WHERE...
2
2380
by: dean.cochrane | last post by:
I have inherited a large application. I have a table which contains a hierarchy, like this CREATE TABLE sample_table( sample_id int NOT NULL parent_sample_id int NOT NULL ....lots of other cols...) DELETEs on all tables are handled by the front end code, which just
13
3812
by: ThePrinceIsRight | last post by:
I have a problem with using a subquery in MS Access. The purpose of the sub-query is to create a list of people who have had doctor exams in the past 6 months and exclude them from the main query. This is what I came up with: SELECT GI.generalinfoid AS GeneralInfoId, max(GI.FirstName) AS FirstName, max(GI.LastName) AS LastName,...
0
7618
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7926
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8132
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7678
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7982
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6286
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
1
2116
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
944
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.