Transact SQL :: How To Get First Table All Rows In Left Join If Condition Is Applied On Second Table

Aug 15, 2015

I am using stored procedure to load gridview but problem is that i am not getting all rows from first table[ Subject] on applying conditions on second table[ Faculty_Subject table] ,as you can see below if i apply condition :-

Faculty_Subject.Class_Id=@Class_Id

Then i don't get all subjects from subject table, how this can be achieved.

Sql Code:-
GO
ALTER Proc [dbo].[SP_Get_Subjects_Faculty_Details]
@Class_Id int
AS BEGIN

[code] ....

View 9 Replies


ADVERTISEMENT

Transact SQL :: Difference Between Inner Join And Left Outer Join In Multi-table Joins?

Oct 8, 2015

I was writing a query using both left outer join and inner join.  And the query was ....

SELECT
        S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
        Production.Suppliers AS S LEFT OUTER JOIN
        (Production.Products AS P
         INNER JOIN Production.Categories AS C

[code]....

However ,the result that i got was correct.But when i did  the same query using the left outer join in both the cases

i.e..

SELECT
        S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
        Production.Suppliers AS S LEFT OUTER JOIN
(Production.Products AS P
LEFT OUTER JOIN Production.Categories AS C
ON C.categoryid = P.categoryid)
ON
S.supplierid = P.supplierid
WHERE
S.country = N'Japan';

The result i got was same,i.e

supplier     country    productid    productname     unitprice    categorynameSupplier QOVFD     Japan     9     Product AOZBW    97.00     Meat/PoultrySupplier QOVFD    Japan   10     Product YHXGE     31.00     SeafoodSupplier QOVFD     Japan   74     Product BKAZJ    10.00     ProduceSupplier QWUSF     Japan    13     Product POXFU     6.00     SeafoodSupplier QWUSF     Japan     14     Product PWCJB     23.25     ProduceSupplier QWUSF    Japan     15    Product KSZOI     15.50    CondimentsSupplier XYZ     Japan     NULL     NULL     NULL     NULLSupplier XYZ     Japan     NULL     NULL     NULL     NULL

and this time also i got the same result.My question is that is there any specific reason to use inner join when join the third table and not the left outer join.

View 5 Replies View Related

Transact SQL :: Left Join To Get Info From A Table With Foreign Keys

Sep 13, 2015

I am still new to SQL and I am having trouble obtaining the results I need from a query. I have worked on this command for some time and searched the internet but cannot seem to still get it correct.

I have a table called Patient. It's primary key is pat_id.

I have a second table called Coverage. It has no primary key. The foreign keys are pat_id, coverage_plan_id, and hosp_status.

I have a third table called Coverage_History.   It has a primary key consisting of pat_id, hosp_status, copay_priority, and effective_from. 

I want to get the pat_id and all the coverage information that is current.   The coverage table contains specific insurance policy information.   The coverage_history table will indicate the effective dates for the coverage. So the tables could contain something like this:

Patient (pat_id and lname)
P123  Monto
P124  Minto
P125  Dento
P126  Donto

Coverage (pat_id, coverage_plan_id, hosp_status, policy_num)
P123     MED1   OP   A1499
P123     ACT4   OP   H39B 
P124     MED1   OP   C90009
P124     RAC    OP   99KKKK
P124     RAC    OP   99KKKK
P124     MED1   OP   C90009
P125     ARP    OP   G190
P126     BCB    OP   H88

Coverage_History (pat_id, hosp_status, copay_priority, effective_from, coverage_plan_id, effective_to)
P123   OP   1   20150102  MED1    NULL
P123   OP   2   20150102  ACT4    NULL
P124   OP   1   20150203  RAC     20150430
P124   OP   2   20150203  MED1    20150430
P124   OP   1   20150501  MED1    NULL
P124   OP   2   20150501  RAC     NULL
P125   OP   1   20150801  ARP     NULL 
P126   OP   1   20150801  BCB     20160101

select p.pat_id, p.lname, ch.coverage_plan_id, ch.hosp_status, ch.effective_from, ch.effective_to, ch.copay_priority,
       from patient p   
     left join
  ( coverage_history ch left join coverage c on ch.coverage_plan_id = c.coverage_plan_id and ch.patient_id = c.patient_id and
                                   (ch.effective_to is NULL or ch.effective_to >= getdate()
)
         ) on ch.patient_id = p.patient_id
        
    where ( ch.effective_to is NULL or ch.effective_to >= getdate() )
   
So I want to see:

P123  Monto  MED1  OP   20150102    NULL       1
P123  Monto  ACT4  OP   20150102    NULL       2
P124  Minto  MED1  OP   20150501    NULL       1
P124  Minto  RAC   OP   20150501    NULL       2
P125  Dento  ARP   OP   20150801    NULL       1
P126  Donto  BCB   OP   20150801    20160101    1

View 6 Replies View Related

Why Is Left Table In LEFT JOIN Limited By Where Clause On Right Table

Jan 25, 2015

-- Why is the left table in a LEFT JOIN limited by the where clause on the right table?eg

DECLARE @LeftTable TABLE (LeftID INT NOT NULL IDENTITY(1, 1), LeftValue INT NULL)
INSERT @LeftTable (LeftValue)
VALUES (111)
INSERT @LeftTable (LeftValue)
VALUES (222)

[code]....

View 2 Replies View Related

Transact SQL :: Left Join Returns Too Many Rows Vertically

Jun 18, 2015

I have a query that based 2 tables. I wrote a query with a left join on the base table but the result set returns multiple rows for each occurrence in the second table because of the left join. I want but to return all records  from on table A and only matching records from table B which id but I would wan tit to keep return them vertically as the because it make it difficult to read when put in a spreadsheet. It want it to return the values horizontally so the rows are not increasing for each occurrence on table b.

View 5 Replies View Related

Condition In Left Outer Join

Jan 22, 2008

Hi, 
I want to get join of two tables A and B in such a way that all the Data from A for a particular Date should be extracted and then from table B Reqired column should selected against that data (it can be null). But if i use the following query:
1) Select A.*,B.Reqired from A Left Outer Join B on A.Same=B.Same Where A.Date = '1/22/2008'
it first joins the Table A and B (A contains millions of records) which takes a lot of time and then where is applied which takes a lot of time.
And if I use the following query:
2)Select A.*,B.Reqired from A Left Outer Join B on A.Same=B.Same AND A.Date = '1/22/2008'
in this case A.Date = '1/22/2008'  has no effect and all the data from the table A comes.
I have also tried first making the temp table for A.Date = '1/22/2008' and the joining with B but its cost is same as 1.
For this purpose Oracle allows the use of (+) operator like:
3)Select A.*,B.Reqired from A,B 
Where A.Same=B.Same(+) AND A.Date = '1/22/2008'  which means all data from A for '1/22/2008' Plus B.Required against it whether its null or not.
Please let me know if there is a way around in MS SQL SERVER 2005.
Thanx.
 
 

View 8 Replies View Related

Some Question About Left Join On Condition?

Oct 31, 2007

Left join on condition has no effect in the left table itself?
I have two tables:
one named student

studentID studentName
-------------------------------------------------- --------------------------------------------------
1 Jom
2 Jim
3 Tom
4 Kate
5 LinDa
6 DaiAnna


The other is grade table

studentID subject grade
-------------------------------------------------- -------------------------------------------------- -----------
1 math 90
2 Chinese 90
1 Chinese 80
3 math 98
4 math 76


And I write two SQLs
1:
select students.studentName , grades.grade as math_grade
from student as students
left outer join grade as grades on students.studentID = grades.studentID and grades.subject = 'math'
2:
select students.studentName , grades.grade as math_grade
from grade as grades
left outer join student as students on students.studentID= grades.studentID and grades.subject = 'math'

After execute, the answer is
1:
studentName math_grade
-------------------------------------------------- -----------
Jom 90
Jim NULL
Tom 98
Kate 76
LinDa NULL
DaiAnna NULL

2:
studentName math_grade
-------------------------------------------------- -----------
Jom 90
NULL 90
NULL 80
Tom 98
Kate 76


The math_grade of the second answer is all the grade rows of the grade table. on grades.subjec='math' has no effect.
Why SQL will act it like this? I know it's not a bug. But I really wanna know the inside work.
Thanks in advance, with very appreciation.

View 4 Replies View Related

Diff Between LEFT OUTER JOIN And *= When Condition

Jul 23, 2005

Using SqlServer :Query 1 :SELECT def.lID as IdDefinition,TDC_AUneValeur.VALEURDERETOUR as ValeurDeRetourFROM serveur.Data_tblDEFINITIONTABLEDECODES def,serveur.Data_tblTABLEDECODEAUNEVALEUR TDC_AUneValeurwhere def.TYPEDETABLEDECODES = 4and TDC_AUneValeur.PERIODE_ANNEEFISCALE_ID = 2and def.lID *= TDC_AUneValeur.DEFINITIONTABLEDECODES_DEFINITION_I DQuery 2 :SELECT def.lID as IdDefinition,TDC_AUneValeur.VALEURDERETOUR as ValeurDeRetourFROM serveur.Data_tblDEFINITIONTABLEDECODES def LEFT OUTER JOINserveur.Data_tblTABLEDECODEAUNEVALEUR TDC_AUneValeurON def.lID = TDC_AUneValeur.DEFINITIONTABLEDECODES_DEFINITION_I Dwhere def.TYPEDETABLEDECODES = 4and TDC_AUneValeur.PERIODE_ANNEEFISCALE_ID = 2The query 1 returns :IdDefinition ValeurDeRetour23 null24 null25 null29 36The query 2 returns :IdDefinition ValeurDeRetour29 36The first result is the good one.How is it that the second query doesn't return the same resultSet ?I've been told about problems comparing NULL ???What is the solution ???Thanks a lot.Damien

View 3 Replies View Related

Left Join Table

Jul 18, 2006

Now I have a table with the table design as following :

table cst_EmpProfile
intEmpId nvcEmpName nvcEmpAddress intEmployeeType bitActiv
1 Peter Null Null true
2 Juli 1, xxxx 2 true
3 Sam Null Null False

table cst_EmpType
intEmpType nvcEmployeeType
1 Free Enginner
2 Manager
3 Operator

To join the table but MUST follow the condition as bitActiv = TRUE:
select emp.nvcEmpName, emp.nvcEmpAddress, ety. nvcEmployeeType from cst_EmpProfile emp left join cst_EmpType on emp.intEmployeeTypee = ety.intEmpType and emp.bitActiv = 1.

But, the sql statement doesnt output the my expected result.
Because the data row return must be 1st and 2nd row as it bitActiv = true.
So, how's I going achieve what i want. tq.

View 1 Replies View Related

Problem With Left Join Table

May 7, 2008

I have a problem when I Left Join this table:

plb_siswa
NSS |NIP |NAMA |JENIS
--------------------------------
28101712 |992002 |ROSIAH |GURU


plb_penataran
NSS |NIP |NAMA_PENATARAN |TAHUN
--------------------------------------------------
28101712 |992002 |KETRAMPILAN |2000
28101712 |992002 |PENYULUH BAHASA INDONESIA |2001


and the result is:

NSS |NIP |NAMA |JENIS|PENATARAN |TAHUN
----------------------------------------------------------------
28101712 |992002 |ROSIAH |GURU |KETRAMPILAN |2000
28101712 |992002 |ROSIAH |GURU |PENYULUH |2001

There are 2 rows with the same person, but I need the result like this:

NSS |NIP |NAMA |JENIS|PENATARAN1 |PENATARAN2|TAHUN1|TAHUN2
--------------------------------------------------------------------
28101712 |992002 |ROSIAH |GURU |KETRAMPILAN |PENYULUH |2000 |2001

How can I join that table to make the result just one record?
Can anybody help me?

View 7 Replies View Related

Keep Order Of Left Table After Join

May 20, 2014

I have an problem with the order of the results after a join.

My first query works fine and the order of field Name ist correct.

Select *
FROM
(SELECT * FROM
dtree A1
WHERE
A1.Subtype=31356
AND
A1.DataID IN
(select DataID from dtreeancestors where AncestorID=9940974)) t

When I do a join the order of the left table changes

Select *
FROM
(SELECT * FROM
dtree A1
WHERE
A1.Subtype=31356
AND
A1.DataID IN
(select DataID from dtreeancestors where AncestorID=9940974)) t, llattrdata A4
WHERE
t.DataID = A4.ID

How can I do a join and keep the order of the left table?

View 4 Replies View Related

Selection At Most 1 Row On 2nd Table In LEFT JOIN

Nov 30, 2006

I have a query that include a single LEFT JOIN. I would like to be able to select at most 1 row of the second table (providing that the JOIN represents a one to many relationship).

Does anyone knows how to do that?
Thanks in advance,
Joannès

View 2 Replies View Related

SQL Server 2014 :: Left Join With A Large Partitioned Table?

Aug 3, 2015

I have a query that has a left join with a large partitioned table. The partitioned table has 10s of millions of records, and each partition has about 100,000 records.

The left join is part of an insert that gets a column from the partitioned table, if the column exists. The query contains the partition ID and all other joined columns are part of a non-clustered index.

Through the profiler, I found that there were millions of reads and the execution plan was giving me a table scan on the partitioned table.

I changed the query to do the insert followed by an update with inner join. That did the trick, but it worries me that SQL Server 2014 behaves differently from 2012 or 2008R2, which can make upgrading very time consuming.

View 3 Replies View Related

I Need To Find The Rows That Exist In One Table But Not In The Other With Condition

Jun 20, 2007

I need to find the rows that exist in one table but not in the otherwith this condition:(prod_name exist in table1 and not in table2.prod_name ) AND(prod_name exist in table1 and not in table2.'S'+prod_name )explanation:i want to know if the product not exit and if the combination of thecharachter "S" with the product Name also not exist at the othertableB.Ryuvi

View 2 Replies View Related

SQL Server 2014 :: 2 Tables Combined Left Join To Primary Key Of A 3 Third Table

Sep 1, 2014

Looking to improve performance of the following code.

It basically generates future days for each dog. So there is a dog table and a day table with every day.

These 2 table cross join and then fill in missing rows. As time moves i will fill in further future dates but will need the initial insert to be a reasonable query.

All columns are covered by index's but the queries at the end take quite a long time. I would hope for index scan to just point out the missing rows especially on the final query.

How to make the last query as fast as possible.

IF OBJECT_ID('dbo.[AllDates]', 'U') IS NOT NULL
DROP TABLE dbo.[AllDates]
CREATE TABLE dbo.[AllDates] (
[Date] date not null PRIMARY KEY
)
;WITH Dates AS

[Code] .....

View 2 Replies View Related

Transact SQL :: Update Table From Another Table For Multiple Rows

Jun 10, 2015

Matrix table has ID column and data below.

ID        Flag     TestDate         Value     Comment                                                                  
111          2       12/15/2014     7.5             null
222         2            Null                10          received

Matrix_Current table could have 1 or multiple rows as below.

ID        Flag               TestDate           Value         Comment
111         2                  01/26/2015        7.9                                                                      
111         2                  02/23/2015        7.9                                                      
111         2                  04/07/2015        6.8
222        1                   null                   8               test comment 1
222        3                   null                   9               test comment 2

When I run below update

 UPDATE  AM
 SET  M.Flag = MC.Flag, M.TestDate = MC.TestDate,
M.Value = MC.Value, M.comment = MC.Comment
 FROM dbo.Matrix M inner join dbo.Matrix_Current MC on M.ID = MC.ID

Matrix table has value below:

ID        Flag     TestDate         Value     Comment                                                                  
111          2       01/26/2015      7.9             
222         1            Null               8            test comment 1

I want to update Matrix table from all row from Matrix_Current, final table would like below:

ID        Flag     TestDate        Value     Comment                                                                  
111          2        04/07/2015      6.8             
222         3            Null                9         test comment 2

View 3 Replies View Related

Three Table Join - Display Newest Comments Left On Photos Created By Members

Jul 6, 2014

I am trying to tweak some code which is used to display the newest comments left on photos created by my members.

The existing code is this:

SELECT top 15 pnumber,pcomment,puser FROM photocomments order by pdate DESC

So the latest comment left was for photo #210879 from user "Cla" (redacted user names). The 2nd newest comment would be for photo #211072 from a member named "mo". pdate is a date field

However for the script I have coded I don't want all of the photo comments to show up. This is because I use access levels based on the type of location (higher levels mean more restricted galleries). I check the access levels as I go through the recordsets.

I use this method to get the top 15 comments:

SELECT top 15 pnumber,pcomment,puser FROM photocomments order by pdate DESC

Now I have to use two other tables to determine the access level. Since PHOTOCOMMENTS is just a list of photo #'s and the people who left comments for those photos, I need to:

a) determine what location the photo is from and
b) determine the access level of that location

I use: select creator,access from locations where id=(select dir from photos where id="&pnumber&")"

This is a two step process as you can see. The first part is:

select dir from photos where id=(pnumber)

ID is the same value as pnumber seen in PHOTOCOMMENTS. That is to say PHOTOS.ID = PHOTOCOMMENTS.PNUMBER

If I haven't confused you yet, the executed code for the first example would be:

select dir from photos where id=210879

which would get me a value for DIR. DIR is the location number which would be:

select creator,access from locations where id=(dir value)

Just to simplify it a bit....

There are three tables (shown below)

PHOTOCOMMENTS
PHOTOS
LOCATIONS

I need to: SELECT top 15 pnumber,pcomment,puser FROM photocomments order by pdate DESC (first table shown)

but then also

select creator,access from locations (The last table shown)
where id=(select dir from photos where id="&pnumber&")"

So the first table PHOTOCOMMENTS has to also join PHOTOS table where PHOTOS.DIR = PHOTOCOMMENTS.PNUMBER in order to get the value of "DIR" and then DIR is joined to the LOCATIONS tables where PHOTOS.DIR = LOCATIONS.ID

Here is the actual code, which I am trying to make into a single SQL command

strSQL = "SELECT top 15 pnumber,pcomment,puser FROM photocomments order by pdate DESC"
set ors = oconn.Execute(strSQL)
tl = 0
do until ors.eof or tl > 15
' until we have 15 results because not every recordset will be of the proper security level

[Code] ....

Bonus points if you can also get it to select from LOCATIONS only WHERE userlevel >= 2

View 4 Replies View Related

T-SQL (SS2K8) :: Delete All Rows Satisfying Certain Condition From Table A And Related Records From B And C

Apr 14, 2015

I have around 3 tables having around 20 to 30gb of data. My table A related to table B by a FK and same way table B related to table C by FK. I would like to delete all rows satisfying certain condition from table A and all corresponding related records from table B and C. I have created a query to delete the grandchild first, followed by child table and finally parent. I have used inner join in my delete query. As you all know, inner join delete operations, are going to be extremely resource Intensive especially on bigger tables.

What is the best approach to delete all these rows? There are many constraints, triggers on these tables. Also, there might be some FK relations to other tables as well.

View 3 Replies View Related

SSMS Express: Creating Parent-Child Table Via LEFT OUTER JOIN - Error Message 156

May 22, 2006

Hi all,

I got an error message 156, when I executed the following code:

////--SQLQueryParent&Child.sql---////////

Use newDB

GO

----Creating dbo.Person as a Parent Table----

CREATE TABLE dbo.Person

(PersonID int PRIMARY KEY NOT NULL,

FirstName varchar(25) NOT NULL,

LastName varchar(25) NOT NULL,

City varchar(25) NOT NULL,

State varchar(25) NOT NULL,

Phone varchar(25) NOT NULL)

INSERT dbo.Person (PersonID, FirstName, LastName, City, State, Phone)

SELECT 1, "George", "Washington", "Washington", "DC", "1-000-1234567"

UNION ALL

SELECT 2, "Abe", "Lincoln", "Chicago", "IL", "1-111-2223333"

UNION ALL

SELECT 3, "Thomas", "Jefferson", "Charlottesville", "VA", "1-222-4445555"

GO

----Creating dbo.Book as a Child table----

CREATE TABLE dbo.Book

(BookID int PRIMARY KEY NOT NULL,

BookTitle varchar(25) NOT NULL,

AuthorID int FOREIGN KEY NOT NULL)

INSERT dbo.Book (BookID, BookTitle, AuthorID)

SELECT 1, "How to Chop a Cherry Tree", 1

UNION ALL

SELECT 2, "Valley Forge Snow Angels", 1

UNION ALL

SELECT 3, "Marsha and ME", 1

UNION ALL

SELECT 4, "Summer Job Surveying Viginia", 1

UNION ALL

SELECT 5, "Log Chopping in Illinois", 2

UNION ALL

SELECT 6, "Registry of Visitors to the White House", 2

UNION ALL

SELECT 7, "My Favorite Inventions", 3

UNION ALL

SELECT 8, "More Favorite Inventions", 3

UNION ALL

SELECT 9, "Inventions for Which the World is Not Ready", 3

UNION ALL

SELECT 10, "The Path to the White House", 2

UNION ALL

SELECT 11, "Why I Do not Believe in Polls", 2

UNION ALL

SELECT 12, "Doing the Right Thing is Hard", 2

GO

---Try to obtain the LEFT OUTER JOIN Results for the Parent-Child Table

SELECT * FROM Person AS I LEFT OUTER JOIN Book ON I.ID=P.ID

GO

////---Results---//////

Msg 156, Level 15, State 1, Line 5

Incorrect syntax near the keyword 'NOT'.

////////////////////////////////////////////////////

(1) Where did I do wrong and cause the Error Message 156?

(2) I try to get a Parent-Child table by using the LEFT OUTER JOIN via the following code statement:

Msg 156, Level 15, State 1, Line 5

Incorrect syntax near the keyword 'NOT'.

Can I get a Parent-Child table after the error 156 is resolved?

Please help and advise.

Thanks,

Scott Chang

View 9 Replies View Related

Transact SQL :: Left Join With Subquery

Aug 24, 2015

SELECT A.EmpId,A.IncidentDate
FROM EmployeePoints1 as A
WHERE IncidentDate=
(SELECT MAX(IncidentDate)
FROM EmployeePoints1
WHERE EmpId = A.EmpId) AND (DATEADD(day,28,DATEADD(WEEK, DATEDIFF(WEEK, 0,A.IncidentDate), 0)) < DATEADD(WEEK, DATEDIFF(WEEK, 0,GetDate()), 0)) AND (A.IncidentCode = 'I' OR A.IncidentCode = 'A')
LEFT JOIN EmployeeTotalPoints1 ON EmployeeTotalPoints1.EmpId = A.EmpId

I am trying to left join another table but  I got

Incorrect syntax near the keyword 'LEFT'.

View 9 Replies View Related

Parent/Child Rows In Report, Nested Table, Textbox Value In Filter Condition

Mar 26, 2008

Hi All,

I am working on SQL server 2005 Reports.
I have one report, one dataset is assigned to it, and one table which displays it.
Now I come accros requirement that, the column value in the filter condition for the table is present in one textbox.

I can not use textbox i.e. reportItems in filter condition. Can someone suggest me how to use textbox value in filters?


I want to display parent/child records on report. I am not getting the proper solution.

The data is like this:

Sequence ItemCode IsParent

1 XYZ 0 'do not have child record

2 PQR 1 'have child records with sequence no 3

3 ASD 0

3 AFDGE 0

3 VDC 0

4 ASR 1 'have child records with sequence no 5
5 ASR 0

If IsParent = 1, that record has child records with sequence = parent sequenece + 1



I think u can understand the data I need to bind, and it is like:

XYZ

+ PQR

ASD

AFDGE

VDC

ASR

On + click we can do show/hide of child records.

I m not getting how to achive this in SQL server report. Can u give some hint?

Thanks in advance
Pravin

View 1 Replies View Related

Left Join Not Returning Rows

Nov 3, 2005

SELECT
[tblSections].[pageTitle],
[tblSections].[sectionURL],
[tblSectionContents].[articleID],
[tblSectionContents].[fileID],
[tblSectionContents].[linkID],
[tblCopy].[copyText],
[tblFiles].[fileName],
[tblFiles].[fileCaption],
[tblGroupings].[grouping],
[tblLinks].[linkURL]
FROM [tblSections]
LEFT JOIN [tblSectionContents] ON [tblSectionContents].[sectionID] = [tblSections].[id]
LEFT JOIN [tblCopy] ON [tblSectionContents].[articleID] = [tblCopy].[id]
LEFT JOIN [tblFiles] ON [tblSectionContents].[fileID] = [tblFiles].[id]
LEFT JOIN [tblGroupings] ON [tblFiles].[groupingID] = [tblGroupings].[id]
LEFT JOIN [tblLinks] ON [tblSectionContents].[linkID] = [tblLinks].[id]
WHERE [tblSections].[id]=2
ORDER BY
[tblSectionContents].[articleID],
[tblSectionContents].[fileID],
[tblSectionContents].[linkID]


If I pass it the ID of a section that has files or copy or [stuff in other tables] attached, then I get a result set that makes sense.

But if I pass it a section ID that doesn't reference any other content tables (ie: the section just has a title and a link URL), I don't get anything back.

Shouldn't it should still get me the fields from the row in tblSections that matches the ID I'm passing it?

How can I make it so that it does?

Thanks :)

View 3 Replies View Related

Transact SQL :: Table Trigger To Delete All Rows Before Inserting Rows

Jul 24, 2015

I have a SQL script to insert data into a table as below:

INSERT into [SRV1INS2].BB.dbo.Agents2
select * from [SRV2INS14].DD.dbo.Agents

I just want to set a Trigger on Agents2 Table, which could delete all rows in the table , before carry out any Insert operation using above statement.I had below Table Trigger on [SRV1INS2].BB.dbo.Agents2 Table as below: But it did not perform what I intend to do.

USE [BB]
GO
/****** Object:  Trigger    Script Date: 24/07/2015 3:41:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

[code]....

View 3 Replies View Related

Transact SQL :: How To Select A Single Record In A Left Join

Sep 16, 2015

My tables look like this:

 Users //
table
 UserID // pk
 UserName // varchar
UserFamilyName // varchar
User_Friends //
table
 FriendsID // pk
 UserID // fk
 FamilyName // varchar

MY query:

 SELECT
U.UserFamilyName, F.FamilyName
 FROM  
Users U LEFT
JOIN User_Friends
F ON U.UserID = 
F.UserID
 WHERE     
U.UserName = ‘JOHN’

How do I adjust my query to select just the very first record from Users_friends, I want only the top first one.And if there are no friends how can I return an empty string instead of Null.

View 10 Replies View Related

Left Join Vs Left Outer Join Syntax Generates Different Execution Plans

Apr 16, 2008



Anyone know why using

SELECT *
FROM a LEFT OUTER JOIN b
ON a.id = b.id
instead of

SELECT *
FROM a LEFT JOIN b
ON a.id = b.id

generates a different execution plan?

My query is more complex, but when I change "LEFT OUTER JOIN" to "LEFT JOIN" I get a different execution plan, which is absolutely baffling me! Especially considering everything I know and was able to research essentially said the "OUTER" is implied in "LEFT JOIN".

Any enlightenment is very appreciated.

Thanks

View 5 Replies View Related

Display All Rows In Left Outer Join (was Would Be So Grateful For Sql Help)

Jan 20, 2005

This is what I want my results to look like

invoice wbs1 wbs2 amount
8060 000-333 500 0
8060 000-333 100 0
8060 000-333 140 0
8060 000-333 150 4335
8060 000-333 160 0
8267 000-333 500 0
8267 000-333 100 20500
8267 000-333 140 547.50
8267 000-333 150 2000
8267 000-333 160 5000


This is what I have so far:

SELECT PR.WBS1, PR.WBS2, ledgerar.invoice, SUM(CASE WHEN ledgerar.transtype = 'in' AND ledgerar.period = '200405' THEN ledgerar.amount * - 1 END) AS amount
FROM PR LEFT OUTER JOIN
LedgerAR ON LedgerAR.WBS1 = PR.WBS1 AND LedgerAR.WBS2 = PR.WBS2 AND LedgerAR.WBS3 = PR.WBS3
WHERE (LedgerAR.wbs1 = '001-333') AND ledgerar.period = '200405'
GROUP BY pr.wbs1, pr.wbs2, ledgerar.invoice


the above query gives me the following results:

invoice wbs1 wbs2 amount
8060 000-333 100 0
8060 000-333 140 0
8060 000-333 160 4335
8267 000-333 100 1320
8267 000-333 140 20912.5
8267 000-333 150 8363
8267 000-333 160 2650


But I don't know how to get the query to display all of wbs2 whether it is null or not. So, for each invoice number there should be five records according to the wbs2 codes (500, 100, 140, 150, 160)

Does anyone know how to do this?

Thanks,
Laura

View 1 Replies View Related

Left Outer Join Not Returning All/null Rows

Dec 31, 2007

Need some join help...

Table 1 - Modules:
ID | Name
1 | A
2 | B
3 | C

Table 2 - CompanyModules
ModuleID | CompanyID
1 | 1
2 | 1
3 | 1
1 | 2


I'd like to return the following result set:
CompanyModules.CompanyID | Modules.Name | Present
1 | A | True
1 | B | True
1 | C | True
2 | A | True
2 | B | False
2 | C | False

What would be the query for this? Thanks.


Edit: This is the query I have tried:


select CompanyModules.CompanyID, Modules.Name, count(Modules.ID) as Present from

CompanyModules RIGHT outer Join Modules on CompanyModules.ModuleID = Modules.ID

group By CompanyModules.CompanyID, Modules.Name

Order by CompanyID


However, it only returns a partial result set:

CompanyModules.CompanyID | Modules.Name | Present
1 | A | 1
1 | B | 1
1 | C | 1
2 | A | 1

View 1 Replies View Related

Transact SQL :: Left Outer Join And Transaction Isolation Level

Nov 30, 2015

We have a service that inserts some rows into a parent table (P) and child table (C). This operation is atomic and performed within a transaction.

We also have a service that queries these tables such that rows are (should only be) returned from P where there are no children for that parent.

The SQL that performs this is simplified below:

SELECT P.SomeCol
FROM P
LEFT OUTER JOIN C ON P.PKofP_Value = C.PkofP_Value
WHERE
C.PkofPValue IS NULL
AND P.SomeOtherCol=0

Our expectation is that the query service should only return rows from P where there are no rows in C.

However, this seems not to be the case, and occasionally we find that rows from P are returned where there are matching rows in C.

We are sure that the process that inserts rows into P and C does so within a single transaction.

We have traced this with SQLTrace and can see the txn stag and committing and all operations using the same transactionid within the transaction.

We are running the default isolation level committed.

In SQLTrace we can see the query process start, the inserter process start and complete and then the query process continue (after presumably being blocked).

So how can the query process "miss" the child rows and return the parent from the above query?

Is it possible that, in this isolation level, the inserter process can block the query process such that when the inserter process commits and when the query process continues it does not see the child rows inserted because they were inserted in the table/index "behind" where the query process has already read - some kind of phantom phenomenon?

View 3 Replies View Related

Transact SQL :: Where Condition - If No Input Value Select All Rows

Apr 27, 2015

I  have table with filed

EmpProject -Table
Empno, Name, Project NO, cost center

I need to restrict the results by project No by user input. In case if user did not provide any value for the projectNO, then need to fetch all rows.

Select empno, name, projecno, cost_center from empproject where projectno=nvl(:pno, :deptno)

View 6 Replies View Related

Transact SQL :: Condition Failed Rows Count

Jul 3, 2015

I am using SQL Server 2008.Each stock item will have default 4 document type (1, 5, 6, 7) and each will have 3 zone's (1, 2, 3) to qualify. Each zone will be updated to 1 for that document type if the item successfully pass through it. If all zone are NULL means no transaction. How to retrieve only the failed rows which means not all zone are 1 or NULL.In the image GJ-00064 has one row failed. So how to get the count of failed rows for each item

Expected result:

Uniid <-> Stockcode <-> FailedRows
1670 <-> GJ-00064 <-> 1

View 8 Replies View Related

Transact SQL :: Using Join With Part Of A Table

Jul 14, 2015

I have a table like this :

reg.no |   description |  start_date |  end_date |   load_date

I want to join this table with itself on reg. no. But not all the rows in table must be joined.

But for example, rows with load_date 01-07-2015 to be joined with rows with load_date 02-07-2015. And the rest of the rows should not used in join (for example, rows having other load_dates)

Is this possible ? and how?

View 4 Replies View Related

Transact SQL :: Get Min Date Row From Join Table

Sep 10, 2015

I have the following 2 tables:

Location:

Policy:

1 Location can be attached to many policies.

I need to create a query to get 1 row per location and get the minimum PolicyBookingDt and RowUpdateDt from the policy table.  All the attributes from the Location table should also be from the Policy that has the minimum PolicyBookingDt.

 So from the above example, i need to get the following:

Getting a little confused on how to create the syntax for this.

View 4 Replies View Related

INNER JOIN Between A CLR-TVF And A Table Returns No Rows

Feb 24, 2007

I have the following query:

select sq.*, p.numero, p.nombre
from paf p right outer join dbo.GetListOfSquaresForShippingLot(@lot) sq on sq.number = p.numero and sq.version = p.numero

The @lot parameter is declared at the top ( declare @lot int; set @lot = 1; ). GetListOfSquaresForShippingLot is a CLR TVF coded in C#. The TVF queries a XML field in the database and returns nodes as rows, and this is completed with information from a table.

If I run a query with the TVF only, it returns data; but if I try to join the TVF with a table, it returns empty, even when I'm expecting matches. I thought the problem was the data from the TVF was been streamed and that's why it could not be joined with the data from the table.

I tried to solve that problem by creating a T-SQL multiline TVF that is supposed to generate a temporary table. This didn't fix the problem.

What can I do? Does anybody know if I can force the TVF to render its data somewhere so the JOIN works? I was thinking a rowset function could help, but I just can't figure out how.

PLEASE HELP!!!!

Let me know if you want the code for the CLR TVF. This is the code for the T-SQL TVF:

CREATE FUNCTION [dbo].[GetTabListOfSquaresForShippingLot]
(
@ShippingLot int
)
RETURNS
@result TABLE
(
Number int, Version int, Position smallint,
SubModel smallint, Quantity smallint,
SquareId nvarchar(5),
ParentSquareId nvarchar(5),
IsSash smallint,
IsGlazingBead smallint,
Width float,
Height float,
GlassNumber smallint,
GlassWidth float,
GlassHeight float
)
AS
BEGIN
INSERT INTO @result
SELECT *
FROM dbo.GetListOfSquaresForShippingLot(@ShippingLot)

RETURN
END

View 6 Replies View Related







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