Showing posts with label below. Show all posts
Showing posts with label below. Show all posts

Thursday, March 29, 2012

Embedded Text Qualifiers no longer supported in Yukon ?

Hello,
I try to import the data below from a text file using the SQL Server 2005
import wizard with a "Flat File Source" and receive the error "SQL Server
Import and Export Wizard / The preview sample contains embedded text
qualifiers ("). The flat file parser does not support embedding text
qualifiers in data. Parsing columns that contain data with text qualifiers
will fail at run time."
With SQL Server 2000 this was no problem. The files I want to import are
about 100MB in size. Any workaround?
select @.@.version returns: Microsoft SQL Server 2005 - 9.00.1314.06 (X64)
Sep 2 2005 21:10:23 Copyright (c) 1988-2005 Microsoft Corporation
Enterprise Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 1)
Sample data:
1 inch,"2""","3 inches","4, 5, and 6""",7 inches,"8"", 9"",""10""""",11
inches
Kind regards,
Frank
Hi Frank...

Found your post here:
http://www.eggheadcafe.com/forumarchives/sqlserverdts/oct2005/post24522404.asp

Any progress in the concerning topic?

Embedded Text Qualifiers no longer supported in Yukon ?

Hello,
I try to import the data below from a text file using the SQL Server 2005
import wizard with a "Flat File Source" and receive the error "SQL Server
Import and Export Wizard / The preview sample contains embedded text
qualifiers ("). The flat file parser does not support embedding text
qualifiers in data. Parsing columns that contain data with text qualifiers
will fail at run time."
With SQL Server 2000 this was no problem. The files I want to import are
about 100MB in size. Any workaround?
select @.@.version returns: Microsoft SQL Server 2005 - 9.00.1314.06 (X64)
Sep 2 2005 21:10:23 Copyright (c) 1988-2005 Microsoft Corporation
Enterprise Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 1)
Sample data:
1 inch,"2""","3 inches","4, 5, and 6""",7 inches,"8"", 9"",""10""""",11
inches
Kind regards,
Frank
Hi Frank...

Found your post here:
http://www.eggheadcafe.com/forumarchives/sqlserverdts/oct2005/post24522404.asp

Any progress in the concerning topic?
|||Check this:
http://www.microsoft.com/downloads/details.aspx?FamilyID=7952c866-807b-4715-80ba-498e0a16ab18&DisplayLang=ensql

Wednesday, March 21, 2012

Email report to Operator

While configure Email reporting to Operator under Database Maintenance
Plan got below mention error...
Error 22022: SQLServerAgent Error: The SQLServerAgent mail session is
not running; check the mail profile and/or the SQLServerAgent service
startup account in the SQLServerAgent properties dialog.
How to overcome this issue?
Please guide!!!!
ThanksDo please check if here is something that can help you:
http://classicasp.aspfaq.com/email/...ning.com/blogs/
<darshaksshah@.gmail.com> wrote in message
news:1169890433.901537.64880@.k78g2000cwa.googlegroups.com...
> While configure Email reporting to Operator under Database Maintenance
> Plan got below mention error...
> Error 22022: SQLServerAgent Error: The SQLServerAgent mail session is
> not running; check the mail profile and/or the SQLServerAgent service
> startup account in the SQLServerAgent properties dialog.
> How to overcome this issue?
> Please guide!!!!
> Thanks
>|||Many Reasons: Out of them
Check to see if your SQL Agent is Running:
Also Check if the DBMail is Started or Setup Properly.
Check SQL Agent is Running under a domain Service Account and if it
has required Priviliges (near to sa) - if the Jobs invlove sending out
Notifications.
I recommend reading BOL more on this.
Maninder
MCDBA
On Jan 27, 4:33 am, darshakss...@.gmail.com wrote:
> While configure Email reporting to Operator under Database Maintenance
> Plan got below mention error...
> Error 22022: SQLServerAgent Error: The SQLServerAgent mail session is
> not running; check the mail profile and/or the SQLServerAgent service
> startup account in the SQLServerAgent properties dialog.
> How to overcome this issue?
> Please guide!!!!
> Thanks

Email report to Operator

While configure Email reporting to Operator under Database Maintenance
Plan got below mention error...
Error 22022: SQLServerAgent Error: The SQLServerAgent mail session is
not running; check the mail profile and/or the SQLServerAgent service
startup account in the SQLServerAgent properties dialog.
How to overcome this issue?
Please guide!!!!
Thanks
Many Reasons: Out of them
Check to see if your SQL Agent is Running:
Also Check if the DBMail is Started or Setup Properly.
Check SQL Agent is Running under a domain Service Account and if it
has required Priviliges (near to sa) - if the Jobs invlove sending out
Notifications.
I recommend reading BOL more on this.
Maninder
MCDBA
On Jan 27, 4:33 am, darshakss...@.gmail.com wrote:
> While configure Email reporting to Operator under Database Maintenance
> Plan got below mention error...
> Error 22022: SQLServerAgent Error: The SQLServerAgent mail session is
> not running; check the mail profile and/or the SQLServerAgent service
> startup account in the SQLServerAgent properties dialog.
> How to overcome this issue?
> Please guide!!!!
> Thanks

Email report to Operator

While configure Email reporting to Operator under Database Maintenance
Plan got below mention error...
Error 22022: SQLServerAgent Error: The SQLServerAgent mail session is
not running; check the mail profile and/or the SQLServerAgent service
startup account in the SQLServerAgent properties dialog.
How to overcome this issue?
Please guide!!!!
ThanksDo please check if here is something that can help you:
http://classicasp.aspfaq.com/email/how-do-i-send-e-mail-from-sql-server.html.
--
Dejan Sarka
http://www.solidqualitylearning.com/blogs/
<darshaksshah@.gmail.com> wrote in message
news:1169890433.901537.64880@.k78g2000cwa.googlegroups.com...
> While configure Email reporting to Operator under Database Maintenance
> Plan got below mention error...
> Error 22022: SQLServerAgent Error: The SQLServerAgent mail session is
> not running; check the mail profile and/or the SQLServerAgent service
> startup account in the SQLServerAgent properties dialog.
> How to overcome this issue?
> Please guide!!!!
> Thanks
>|||Many Reasons: Out of them
Check to see if your SQL Agent is Running:
Also Check if the DBMail is Started or Setup Properly.
Check SQL Agent is Running under a domain Service Account and if it
has required Priviliges (near to sa) - if the Jobs invlove sending out
Notifications.
I recommend reading BOL more on this.
Maninder
MCDBA
On Jan 27, 4:33 am, darshakss...@.gmail.com wrote:
> While configure Email reporting to Operator under Database Maintenance
> Plan got below mention error...
> Error 22022: SQLServerAgent Error: The SQLServerAgent mail session is
> not running; check the mail profile and/or the SQLServerAgent service
> startup account in the SQLServerAgent properties dialog.
> How to overcome this issue?
> Please guide!!!!
> Thanks

Monday, March 19, 2012

email on insert

Hi all,

I wanted sql server to shoot an email upon insert into a table. I treated a
trigger on that table as below.

CREATE TRIGGER [emailoninsert] ON [dbo].[table_name]
FOR INSERT
AS
exec sp_sendSMTPmail 'user@.user.com', 'New records are inserted in
table_name table', 'Please investigate and take necessary actions.',
@.cc='', @.BCC = '',
@.Importance=1,
@.Attachments='', @.HTMLFormat = 0,@.From =
'notification@.sqlserver.com'

Is this solution a good method?

Thanks,

Guju"Guju" <patelroshanr@.yahoo.com.au> wrote in message
news:42508c0c_1@.news.iprimus.com.au...
> Hi all,
> I wanted sql server to shoot an email upon insert into a table. I treated
a
> trigger on that table as below.
> CREATE TRIGGER [emailoninsert] ON [dbo].[table_name]
> FOR INSERT
> AS
> exec sp_sendSMTPmail 'user@.user.com', 'New records are inserted in
> table_name table', 'Please investigate and take necessary actions.',
> @.cc='', @.BCC = '',
> @.Importance=1,
> @.Attachments='', @.HTMLFormat = 0,@.From =
> 'notification@.sqlserver.com'
>
> Is this solution a good method?

No.

It will greatly slow down insert speeds.

> Thanks,
> Guju|||Guju wrote:
> Hi all,
> I wanted sql server to shoot an email upon insert into a table. I
treated a
> trigger on that table as below.
> CREATE TRIGGER [emailoninsert] ON [dbo].[table_name]
> FOR INSERT
> AS
> exec sp_sendSMTPmail 'user@.user.com', 'New records are inserted in
> table_name table', 'Please investigate and take necessary actions.',
> @.cc='', @.BCC = '',
> @.Importance=1,
> @.Attachments='', @.HTMLFormat = 0,@.From =
> 'notification@.sqlserver.com'
>
> Is this solution a good method?
> Thanks,
> Guju

It may be a better idea to create a script that checks for new records
in the table every x number of hours (run it as an sql agent job).
the script may save the last record id that it already saw in a table
for this purpose.
As mentioned above, the solution you implemented means the email is
sent at the expense of the insert statement , making it horribly slow.
My way you can also send one mail if 10 records were inserted in stead
of 10, with the data of all 10, which you may trust me is more useful
to the sorry person actually receiving these mails.

hope this helps.

Tzvika|||Is it possible for you to post a sample script..I am attempting to get
the same result as the author.|||Is it possible for you to post a sample script..I am attempting to get
the same result as the author.

Sunday, March 11, 2012

email attachment corrupted

We are receiving the below error when reports are sent using subscriptions
Using Adobe Read 6.0, I get the following error "Adobe Reader could not open
'report.pdf' because it is either not a supported file type or because the
file has been corrupted
Our client is using lotus notes 4.5 server. I saw something in the
knowledge base that says this issue has been seen before but I have not seen
any resolution to this. Is there a service pack or a configuration setting I
can change to solve this issue.We have issued a QFE for this problem. Currently it is only available
through PSS. The KB reference is 872774, however the article has not yet
been posted on msdn.
--
-Daniel
This posting is provided "AS IS" with no warranties, and confers no rights.
"Kevin O" <KevinO@.discussions.microsoft.com> wrote in message
news:D51D8FB7-22C3-47CE-933C-A7EEAED8EBDE@.microsoft.com...
> We are receiving the below error when reports are sent using subscriptions
> Using Adobe Read 6.0, I get the following error "Adobe Reader could not
open
> 'report.pdf' because it is either not a supported file type or because the
> file has been corrupted
> Our client is using lotus notes 4.5 server. I saw something in the
> knowledge base that says this issue has been seen before but I have not
seen
> any resolution to this. Is there a service pack or a configuration
setting I
> can change to solve this issue.|||Thanks for the help. For all others that run into this issue here is a link
where you can download the fix.
http://support.microsoft.com/default.aspx?scid=kb;en-us;872774
"Daniel Reib [MSFT]" wrote:
> We have issued a QFE for this problem. Currently it is only available
> through PSS. The KB reference is 872774, however the article has not yet
> been posted on msdn.
> --
> -Daniel
> This posting is provided "AS IS" with no warranties, and confers no rights.
>
> "Kevin O" <KevinO@.discussions.microsoft.com> wrote in message
> news:D51D8FB7-22C3-47CE-933C-A7EEAED8EBDE@.microsoft.com...
> > We are receiving the below error when reports are sent using subscriptions
> >
> > Using Adobe Read 6.0, I get the following error "Adobe Reader could not
> open
> > 'report.pdf' because it is either not a supported file type or because the
> > file has been corrupted
> >
> > Our client is using lotus notes 4.5 server. I saw something in the
> > knowledge base that says this issue has been seen before but I have not
> seen
> > any resolution to this. Is there a service pack or a configuration
> setting I
> > can change to solve this issue.
>
>

Sunday, February 26, 2012

else if statement


I have this function and is given me the error below the code and want to know which is my mistake

create function pt
(@.idpt INT,
@.option INT)
Returns Real
AS
Begin
if (@.option=1)
Begin
Return ( select sqrt(a.px*a.px + a.py*a.py)
from electron as a
where @.idpt = a.idap)
end
else if(@.option=2)
Begin
Return ( select sqrt(a.px*a.px + a.py*a.py)
from muon as a
where @.idpt = a.idap)
End
else
Begin
Return ( select sqrt(a.px*a.px + a.py*a.py)
from jet as a
where @.idpt = a.idap)
end
end

Msg 455, Level 16, State 2, Procedure pt, Line 22
The last statement included within a function must be a return statement.
Try putting a dummy "RETURN NULL" after the large IF block. I think the compiler isn't realizing that at least one of the 3 return statements you've got will always be called, and it's throwing a fit. The extra RETURN will never get called, but it'll at least keep the compiler happy.
|||

Try the code below.

Chris

Code Snippet

CREATE FUNCTION pt (@.idpt INT, @.option INT)

RETURNS REAL

AS

BEGIN

DECLARE @.Output REAL

IF (@.option = 1)

BEGIN

SELECT @.Output = SQRT(a.px * a.px + a.py * a.py)

FROM electron AS a

WHERE @.idpt = a.idap

END

ELSE

IF (@.option = 2)

BEGIN

SELECT @.Output = SQRT(a.px * a.px + a.py * a.py)

FROM muon AS a

WHERE @.idpt = a.idap

END

ELSE

BEGIN

SELECT @.Output = SQRT(a.px * a.px + a.py * a.py)

FROM jet AS a

WHERE @.idpt = a.idap

END

RETURN @.Output

END

Eliminate top and bottom percent of records

I have a temp table that is being populated and below is a representation of the data.Basically, for each mile_code and rep combination there will be ‘X’ number of records.(In the example below there are 30 records.)What I need to do is eliminate the top and bottom 10% (This could be any percentage and I want to be able to change that easily if I have to.) of DeltaT for each mile_code and rep combination and then average the remaining values in DeltaT for each mile_code and rep combination.

I’ve tried a bunch of different approaches and none give me what I’m looking for.Any ideas or solutions?

mile_code DeltaT rep close_date

Approach 1 Coleman 6/5/2007 16:52

Approach 1 COLEMAN 6/5/2007 14:32

Approach 1 COLEMAN 6/5/2007 9:26

Approach 21 COLEMAN 5/31/2007 14:07

Approach 14 COLEMAN 5/31/2007 9:53

Approach 7 Coleman 5/30/2007 16:12

Approach 36 COLEMAN 5/29/2007 15:53

Approach 8 COLEMAN 5/29/2007 13:54

Approach 8 COLEMAN 5/29/2007 13:23

Approach 8 COLEMAN 5/29/2007 9:00

… (20 more records)

Interview 1 Coleman 6/5/2007 16:52

Interview 1 COLEMAN 6/5/2007 14:32

Interview 1 COLEMAN 6/5/2007 9:26

Interview 8 COLEMAN 5/29/2007 13:54

Interview 8 COLEMAN 5/29/2007 9:00

Interview 14 COLEMAN 5/25/2007 8:37

Interview 61 COLEMAN 5/24/2007 10:57

Interview 14 COLEMAN 5/23/2007 9:32

Interview 26 COLEMAN 5/18/2007 9:39

Interview 23 Coleman 5/14/2007 13:25

… (20 more records)

Followed by 30 each of the other 3 milecodes for Coleman

Approach 0 DOLAN 6/6/2007 9:27

Approach 1 DOLAN 6/5/2007 13:39

Approach 1 DOLAN 6/5/2007 12:20

Approach 1 DOLAN 6/5/2007 11:37

Approach 92 DOLAN 6/5/2007 11:12

Approach 91 DOLAN 6/5/2007 9:44

Approach 2 Dolan 6/4/2007 11:53

Approach 2 DOLAN 6/4/2007 11:11

Approach 5 Dolan 6/1/2007 16:07

Approach 177 DOLAN 6/1/2007 10:58

… (20 more records)

Interview 96 DOLAN 6/5/2007 16:38

Interview 167 DOLAN 6/5/2007 14:24

Interview 2 Dolan 6/4/2007 14:54

Interview 2 DOLAN 6/4/2007 11:11

Interview 5 Dolan 6/1/2007 16:07

Interview 27 DOLAN 6/1/2007 14:48

Interview 323 DOLAN 6/1/2007 13:49

Interview 15 Dolan 6/1/2007 11:48

Interview 224 DOLAN 5/31/2007 16:40

Interview 126 Dolan 5/30/2007 15:02

… (20 more records)

…

Here is one way.

Code Snippet

select *

from tb t1

where t1.deltat in (select top 90 percent t2.deltat from tb t2 where t2.mile_code=t1.mile_code order by t2.deltat asc)

and t1.deltat in (select top 90 percent t3.deltat from tb t3 where t3.mile_code=t1.mile_code order by t3.deltat desc)

|||

What should be the criteria to eliminate the top and bottom 10 % of [DeltaT], other than [mile_code] and [rep]?

Should we sort by [mile_code], [rep] and [DeltaT] and then eliminate the top and bottom 10%?

AMB

|||I thought of this on the way to work this morning and realized the way I described what I wanted was incorrect. If the data is sorted by DeltaT for each mile_code and rep combination then in this example (30 records for each group and 10% gone from top to bottom) the first 3 records and last 3 records should be removed. So it doesn't matter what the values of DeltaT are. If there were fractions caused by the number of records chosen and/or the percentage then I'd want it to just round to the nearest whole number.|||

Try:

Code Snippet

createtable #t (

mile_code varchar(25)notnull,

rep varchar(25)notnull,

deltat intnotnull

)

go

declare @.i int, @.j int

declare @.mile_code varchar(25)

declare @.rep varchar(25)

set @.j = 1

while @.j <= 2

begin

set @.rep =

case

when @.j = 1 then'COLEMAN'

when @.j = 2 then'DOLAN '

end

set @.i = 1

while @.i <= 60

begin

set @.mile_code =

case

when @.i between 1 and 30 then'Approach'

when @.i between 31 and 60 then'Interview'

end

insertinto #t values(@.mile_code, @.rep,(abs(checksum(newid()))% 100)+ 1)

set @.i = @.i + 1

end

set @.j = @.j + 1

end

go

declare @.percent int

set @.percent = 10

;with cte

as

(

select

mile_code,

rep,

deltat,

((row_number()over(partitionby mile_code, rep orderby deltat))* 100.00)/(count(*)over(partitionby mile_code, rep))as pct

from

#t

)

select

mile_code,

rep,

avg(deltat)as avg_deltat

from

cte

where

pct between @.percent and (100.00 - @.percent)

groupby

mile_code,

rep

orderby

mile_code,

rep

go

droptable #t

go

AMB

|||

I am not perfectly clear about what you are trying to do, but here is a solution that removes the top 10 percent using a CTE and a couple of aggregates. Note this will only work in 2005...

;with rowCounts as (

select row_number() over (partition by mile_code,rep order by closeDate) as rowNum, --gives a row number per group, ordered by close date
count(*) over (partition by mile_code,rep) as totalRows, --gets total rows by mile_code and rep. This is how I do the work later
mile_code,rep, deltaT, closeDate
from #t) --this is the same as his #t, plus the close date. I will repeat it after this explanation

select mile_code,rep, deltaT, closeDate, rowNum, totalRows
from rowCounts
where rowNum > totalRows * (@.percent / 100.0) --removes the bottom 10 percent
and rowNum < totalRows - (totalRows * (@.percent / 100.0)) -- removes the top

The whole code (thanks to hunchback):

set nocount on
create table #t (
mile_code varchar(25) not null,
rep varchar(25) not null,
deltat int not null,
closeDate datetime
)
go
declare @.i int, @.j int
declare @.mile_code varchar(25)
declare @.rep varchar(25)
declare @.closeDate datetime
set @.j = 1
while @.j <= 2
begin
set @.rep =
case
when @.j = 1 then 'COLEMAN'
when @.j = 2 then 'DOLAN '
end
set @.i = 1

while @.i <= 60
begin
set @.mile_code =
case
when @.i between 1 and 22 then 'Approach'
when @.i between 23 and 60 then 'Interview'
end
insert into #t values(@.mile_code, @.rep, (abs(checksum(newid())) % 100) + 1,
dateadd(day,(abs(checksum(newid())) % 100) + 1,'20070101'))
set @.i = @.i + 1
end
set @.j = @.j + 1
end

go

declare @.percent int
set @.percent = 10
;with rowCounts as (
select row_number() over (partition by mile_code,rep order by closeDate) as rowNum,
count(*) over (partition by mile_code,rep) as totalRows,
mile_code,rep, deltaT, closeDate
from #t)
select mile_code,rep, deltaT, closeDate, rowNum, totalRows
from rowCounts
where rowNum > totalRows * (@.percent / 100.0)
and rowNum < totalRows - (totalRows * (@.percent / 100.0))

drop table #t

go

|||here's another alternative,

again, thanks to hunchback for the test data

create table #t (
mile_code varchar(25) not null,
rep varchar(25) not null,
deltat int not null
)
go

declare @.i int, @.j int
declare @.mile_code varchar(25)
declare @.rep varchar(25)
set @.j = 1

while @.j <= 2
begin
set @.rep =
case
when @.j = 1 then 'COLEMAN'
when @.j = 2 then 'DOLAN '
end

set @.i = 1

while @.i <= 60
begin
set @.mile_code =
case
when @.i between 1 and 30 then 'Approach'
when @.i between 31 and 60 then 'Interview'
end

insert into #t values(@.mile_code, @.rep, (abs(checksum(newid())) % 100) + 1)
set @.i = @.i + 1
end

set @.j = @.j + 1
end
go

SELECT IDENTITY(int,1,1) AS row_number
, *
INTO #a
FROM #t
ORDER BY
mile_code
, rep
, deltat

DECLARE @.percnt int
SET @.percnt = 10

SELECT a.mile_code
, a.rep
, a.deltat
, row_number - minrow AS grp_row_number
, maxrow * (@.percnt/100.0) as countpergrp
FROM #a a INNER JOIN
(
SELECT mile_code
, rep
, MIN(row_number) - 1 AS minrow
, COUNT(*) AS maxrow
FROM #a
GROUP BY
mile_code
, rep
) b on a.mile_code = b.mile_code
and a.rep = b.rep
WHERE row_number - minrow between (maxrow * (@.percnt/100.0)) and (maxrow - (maxrow * (@.percnt/100.0)))

DROP TABLE #t
DROP TABLE #a
GO|||

Thanks everyone. Still have a little more work to do to get the final result before putting it into producton (Have to add some other calculations but will do that by joining in another temp table or something.) but all of your input helped a lot. Here is what I ended up with thanks to your help:

DECLARE @.percent int,

@.recentindex int

SET @.percent = 10

SET @.recentindex = 45

Then crate temp table #miledata to get the last 'x' number of records for each rep in each mile_code that they have completed. Do this based off of the @.recentindex variable.

Then use either of the following to get results. Haven't decided which I'll put into production yet.

OPTION A

/*This creates a common table expression to run our aggregate query against.*/

;WITH cte_AveRecords AS

(

SELECT row_number() OVER(partition BY mile_code, rep ORDER BY deltaT) AS rowNum, --gives a row number per group, ordered by deltaT

COUNT(*) OVER (partition BY mile_code, rep) AS totalRows, --gets total rows by mile_code and rep.

mile_code,

rep,

deltaT,

recentindex

FROM#miledata

)

/*This deterimines the average per mile_code and rep by selecting the rows that fall above the low percent and less than or equal to the upper percent.*/

SELECT c.mile_code,

c.rep,

CAST(AVG(CAST(a.deltaT AS Decimal(5,1))) AS Decimal(5,1)) AS AvgTime

FROM

(

SELECT mile_code, rep, deltaT, recentindex, rowNum, totalRows

FROM cte_AveRecords

WHERE rowNum > totalRows * (@.percent / 100.0) --removes the bottom 'x' percent

AND rowNum < totalRows - (totalRows * (@.percent / 100.0)) -- removes the top

)a

JOIN cte_AveRecords c ON a.rep = c.rep AND a.mile_code = c.mile_code

GROUP BY c.mile_code,

c.rep

ORDER BY c.rep,

c.mile_code

OPTION B

/*This creates a common table expression to run our aggregate query against.*/

;WITH cte_AveRecords AS

(

SELECT

mile_code,

rep,

deltat,

/*This assigns a percentage to each row number in the mile_code and rep group.See explaination A below*/

((row_number() over(partition by mile_code, rep order by deltat)) * 100.00) / (count(*) over(partition by mile_code, rep)) as pct

FROM #miledata

)

/*This deterimines the average per mile_code and rep based on what we populated the CTE with..*/

SELECT mile_code,

rep,

CAST(AVG(CAST(deltat AS Decimal(5,1))) AS Decimal(5,1)) AS avg_deltat

FROM cte_AveRecords

WHERE pct > @.percent and pct < (100.00 - @.percent)

GROUP BY mile_code,

rep

ORDER BY rep,

mile_code

GO

Sunday, February 19, 2012

efficient JOIN query

Please help me with the efficient JOIN query to bring the below result :

create table pk1(col1 int)
create table pk2(col1 int)
create table pk3(col1 int)
create table fk(col1 int, col2 int NOT NULL, col3 int, col4 int)

insert into pk1 values(1)
insert into pk1 values(2)
insert into pk1 values(3)
insert into pk2 values(1)
insert into pk2 values(2)
insert into pk2 values(3)
insert into pk3 values(1)
insert into pk3 values(2)
insert into pk3 values(3)
insert into fk values(1, 1, null, 10)
insert into fk values(null, 1, 1, 20)
insert into fk values(1, 1,null, 30)
insert into fk values(1, 1, null, 40)
insert into fk values(1, 1, 1, 70)
insert into fk values(2, 3, 1, 60)
insert into fk values(1, 1, 1, 100)
insert into fk values(2, 2, 3, 80)
insert into fk values(null, 1, 2, 50)
insert into fk values(null, 1, 4, 150)
insert into fk values(5, 1, 2, 250)
insert into fk values(6, 7, 8, 350)
insert into fk values(10, 1, null, 450)
Below query will give the result :
select fk.* from fk inner join pk1 on pk1.col1 = fk.col1 inner join pk2 on pk2.col1 = fk.col2 inner join pk3 on pk3.col1 = fk.col3
Result :
+++++
| col1 | col2 | col3 | col4 |
+++++
| 1 | 1 | 1 | 70 |
| 2 | 3 | 1 | 60 |
| 1 | 1 | 1 | 100 |
| 2 | 2 | 3 | 80 |
+++++
But I require also the NULL values in col1 and col3
Hence doing the below :
select distinct fk.* from fk inner join pk1 on pk1.col1 = fk.col1 or fk.col1 is null inner join pk2 on pk2.col1 = fk.col2 inner join pk3 on pk3.col1 = fk.col3 or fk.col3 is null
+++++
| col1 | col2 | col3 | col4 |
+++++
| null | 1 | 1 | 20 |
| null | 1 | 2 | 50 |
| 1 | 1 | null | 10 |
| 1 | 1 | null | 30 |
| 1 | 1 | null | 40 |
| 1 | 1 | 1 | 70 |
| 1 | 1 | 1 | 100 |
| 2 | 2 | 3 | 80 |
| 2 | 3 | 1 | 60 |
+++++
The above is the reqd output, but the query will be very slow if there are more NULL valued rows in col1 and col3, since I need to also use distinct if I use 'IS NULL' check in JOIN.
Please let me know if there is an aliternative to this query which can return the same result set in an efficient manner.

Hi

The

INNER JOIN ... ON <field1> = <field2> OR <field1> IS NULL

can be replaces with

LEFT OUTER JOIN .... ON <field1> = <field2>

And an INNER JOIN needs to precede all other joins , so the resulting SELECT will look like :

select distinct fk.*
from fk
inner join pk2
on k2.col1 = fk.col2
LEFT OUTER JOIN pk1
on pk1.col1 = fk.col1
LEFT OUTER JOIN pk3
on pk3.col1 = fk.col3

|||But the LEFT JOIN does not give the expected result(i,.e 9 rows) I have posted, it gives 12 rows which is not the expected result.|||SELECT DISTINCT fk.col1, fk.col2, fk.col3, fk.col4
FROM fk FULL OUTER JOIN
pk1 ON fk.col1 = pk1.col1 FULL OUTER JOIN
pk3 ON fk.col3 = pk3.col1 FULL OUTER JOIN
pk2 ON fk.col2 = pk2.col1
|||Example of using where clause to filter.
SELECT fk.col1, fk.col2, fk.col3, fk.col4
FROM fk FULL OUTER JOIN
pk1 ON fk.col1 = pk1.col1 FULL OUTER JOIN
pk3 ON fk.col3 = pk3.col1 FULL OUTER JOIN
pk2 ON fk.col2 = pk2.col1
WHERE (fk.col1 IS NULL) OR
(fk.col3 IS NULL)

efficient JOIN query

Please help me with the efficient JOIN query to bring the below result :

create table pk1(col1 int)

create table pk2(col1 int)

create table pk3(col1 int)

create table fk(col1 int, col2 int NOT NULL, col3 int, col4 int)

insert into pk1 values(1)
insert into pk1 values(2)
insert into pk1 values(3)

insert into pk2 values(1)
insert into pk2 values(2)
insert into pk2 values(3)

insert into pk3 values(1)
insert into pk3 values(2)
insert into pk3 values(3)

insert into fk values(1, 1, null, 10)
insert into fk values(null, 1, 1, 20)
insert into fk values(1, 1,null, 30)
insert into fk values(1, 1, null, 40)
insert into fk values(1, 1, 1, 70)
insert into fk values(2, 3, 1, 60)
insert into fk values(1, 1, 1, 100)
insert into fk values(2, 2, 3, 80)
insert into fk values(null, 1, 2, 50)
insert into fk values(null, 1, 4, 150)
insert into fk values(5, 1, 2, 250)
insert into fk values(6, 7, 8, 350)
insert into fk values(10, 1, null, 450)

Below query will give the result :

select fk.* from fk inner join pk1 on pk1.col1 = fk.col1 inner join pk2 on pk2.col1 = fk.col2 inner join pk3 on pk3.col1 = fk.col3

Result :
+--+--+--+--+
| col1 | col2 | col3 | col4 |
+--+--+--+--+
| 1 | 1 | 1 | 70 |
| 2 | 3 | 1 | 60 |
| 1 | 1 | 1 | 100 |
| 2 | 2 | 3 | 80 |
+--+--+--+--+

But I require also the NULL values in col1 and col3

Hence doing the below :

select distinct fk.* from fk inner join pk1 on pk1.col1 = fk.col1 or fk.col1 is null inner join pk2 on pk2.col1 = fk.col2 inner join pk3 on pk3.col1 = fk.col3 or fk.col3 is null

+--+--+--+--+
| col1 | col2 | col3 | col4 |
+--+--+--+--+
| null | 1 | 1 | 20 |
| null | 1 | 2 | 50 |
| 1 | 1 | null | 10 |
| 1 | 1 | null | 30 |
| 1 | 1 | null | 40 |
| 1 | 1 | 1 | 70 |
| 1 | 1 | 1 | 100 |
| 2 | 2 | 3 | 80 |
| 2 | 3 | 1 | 60 |
+--+--+--+--+

The above is the reqd output, but the query will be very slow if there are more NULL valued rows in col1 and col3, since I need to also use distinct if I use 'IS NULL' check in JOIN.

Please let me know if there is an aliternative to this query which can return the same result set in an efficient manner.Hi

I've just written some SQL and looked back at your previous post and seen I've pretty well written what BM & Mallier suggested.

Indexes (major effect):
CREATE UNIQUE INDEX pk1_idx1 ON pk1(col1)
CREATE UNIQUE INDEX pk2_idx1 ON pk2(col1)
CREATE UNIQUE INDEX pk3_idx1 ON pk3(col1)
CREATE INDEX fk_idx1 ON fk(col1)
CREATE INDEX fk_idx2 ON fk(col2)
CREATE INDEX fk_idx3 ON fk(col3)

UNION (minor effect):
select DISTINCT
fk.*
from fk inner join
pk1 on
pk1.col1 = fk.col1
or fk.col1 is null
inner join pk2
on pk2.col1 = fk.col2
inner join pk3 on
pk3.col1 = fk.col3
or fk.col3 is null

select fk.*
from fk inner join
pk1 on
pk1.col1 = fk.col1
inner join pk2
on pk2.col1 = fk.col2
inner join pk3 on
pk3.col1 = fk.col3
UNION ALL
SELECT fk.*
FROM fk
inner join pk2 on
pk2.col1 = fk.col2
WHERE fk.col1 IS NULL
AND fk.col3 IS NULL
UNION ALL
SELECT fk.*
FROM fk
inner join pk2 on
pk2.col1 = fk.col2
INNER JOIN pk1 ON
pk1.col1 = fk.col1
WHERE fk.col3 IS NULL
UNION ALL
SELECT fk.*
FROM fk
inner join pk2 on
pk2.col1 = fk.col2
INNER JOIN pk3 ON
pk3.col1 = fk.col3
WHERE fk.col1 IS NULL


Once the indexes are added the UNION comes out slightly better on the plan but probably not worth the hassle of such an inflexible query.

Also - only selecting the columns you actually need would be good practice(when it comes to the real query).

HTH|||with less data ,its difficult say which query is best,though below below code is more efficient than query u posted. this query can avoid distinct key word.Consider index which mentioned by pootle
--selection query--

select
fk.*
from
fk
where
exists(select
null
from
pk1
where pk1.col1 = fk.col1 or fk.col1 is null)
and exists( select
null
from
pk2
where pk2.col1 = fk.col2 or fk.col1 is null)
and exists( select
null
from
pk3
where pk3.col1 = fk.col3 or fk.col3 is null)



Comparison

set statistics profile on
set statistics io on
--ur query without any index---
select distinct fk.*
from fk inner join pk1 on pk1.col1 = fk.col1 or fk.col1 is null
inner join pk2 on pk2.col1 = fk.col2
inner join pk3 on pk3.col1 = fk.col3 or fk.col3 is null
/*
Table 'pk3'. Scan count 16, logical reads 16, physical reads 0, read-ahead reads 0.
Table 'pk1'. Scan count 12, logical reads 12, physical reads 0, read-ahead reads 0.
Table 'pk2'. Scan count 13, logical reads 13, physical reads 0, read-ahead reads 0.
Table 'fk'. Scan count 1, logical reads 1, physical reads 0, read-ahead reads 0.
*/


-- improved query without any index--
select
fk.*
from
fk
where
exists(select
null
from
pk1
where pk1.col1 = fk.col1 or fk.col1 is null)
and exists( select
null
from
pk2
where pk2.col1 = fk.col2 or fk.col1 is null)
and exists( select
null
from
pk3
where pk3.col1 = fk.col3 or fk.col3 is null)
/*
Table 'pk3'. Scan count 10, logical reads 10, physical reads 0, read-ahead reads 0.
Table 'pk2'. Scan count 10, logical reads 10, physical reads 0, read-ahead reads 0.
Table 'pk1'. Scan count 13, logical reads 13, physical reads 0, read-ahead reads 0.
Table 'fk'. Scan count 1, logical reads 1, physical reads 0, read-ahead reads 0.

It execute 1 step less than previous query

*/