Strange Query Plan

Mar 19, 2008

I have a query like below .. if i add where Served = 1 , the query takes foreever... if i remove it, it takes only 6 sec...

I am not sure why this is hapening?


select distinct a.Episode_Key,
case when ag.Category IN ('ASMI', 'COOC', 'SPCL') then 'SMI'
when ag.Category = 'SEDC' then 'SED'
when ag.Category = 'ACCA' then 'SA'
when ag.Category like 'CGA%' then 'Gam'
end as [Category],
ag.Agreement_Type_Name as [Agreement],
p.ServiceProvider,
s2.Served
from dbo.Assessment a
INNER JOIN (
select distinct Episode_Key, p.ServiceProvider, max(CSDS_Object_Key) as [Sequence]
from dbo.Assessment a
INNER JOIN dbo.CD_Provider_Xref p
ON a.Provider_CD = p.Provider_CD
where Creation_DT >= '07/01/2007'
and Reason_CD = 1
group by Episode_Key, p.ServiceProvider
) as s1
ON a.CSDS_Object_Key = s1.Sequence
INNER JOIN dbo.CD_Provider_XREF p
ON a.Provider_CD = p.Provider_CD
INNER JOIN dbo.CD_Agreement_Type ag
ON ag.Agreement_Type_CD = a.Agreement_Type_CD
LEFT OUTER JOIN (
select distinct Episode_Key, p.ServiceProvider,
1 as [Served]
from dbo.Encounters e
INNER JOIN dbo.CD_Provider_Xref p
ON e.Provider_CD = p.Provider_CD
where Encounter_Begin_DT between '01/01/2008' and '01/31/2008'
and Procedure_CD is not null
and Encounter_Units > 0
) as s2
ON a.Episode_Key = s2.Episode_Key
and p.ServiceProvider = s2.ServiceProvider
????---where Served = 1
group by a.Episode_Key, ag.Agreement_Type_Name, p.ServiceProvider, Served,
case when ag.Category IN ('ASMI', 'COOC', 'SPCL') then 'SMI'
when ag.Category = 'SEDC' then 'SED'
when ag.Category = 'ACCA' then 'SA'
when ag.Category like 'CGA%' then 'Gam'
End

View 2 Replies


ADVERTISEMENT

Using Execution Plan Generates Strange Errors

Feb 27, 2007

After installing SP2 for SQL Serve 2005, I get strange errors when using either "Estimated Execution Plan" or "Actual Execution Plan".

Using "Estimated Execution Plan" generates this error
An error occurred while executing batch. Error message is: Error processing execution plan results. The error message is:
There is an error in XML document (1, 3998).
Unexpected end of file while parsing has occurred. Line 1, position 3998.

Using "Actual Execution Plan" generates this error
An error occurred while executing batch. Error message is: Error processing execution plan results. The error message is:
There is an error in XML document (1, 4001).
Unexpected end of file has occurred. The following elements are not closed: RelOp, ComputeScalar, RelOp, Update, RelOp, QueryPlan, StmtSimple, Statements, Batch, BatchSequence, ShowPlanXML. Line 1, position 4001.

All I do is testing this solutiondeclare@t table (dt datetime)

insert@t
select'02-Jan-2007' union all
select'01-Feb-2007' union all
select'10-Feb-2007' union all
select'28-Feb-2007' union all
select'18-Mar-2007'

DECLARE@DaysRange INT,
@NumOfCalls INT

SELECT@DaysRange = 35,
@NumOfCalls = 4

SELECTt1.dt AS theDate
FROM@t AS t1
CROSS JOIN@t AS t2
WHEREt2.dt >= DATEADD(day, DATEDIFF(day, 0, t1.dt), 0)
AND t2.dt < DATEADD(day, DATEDIFF(day, 0, t1.dt), @DaysRange)
OR
t2.dt >= DATEADD(day, DATEDIFF(day, @DaysRange, t1.dt), 1)
AND t2.dt < DATEADD(day, DATEDIFF(day, 0, t1.dt), 1)
GROUP BYt1.dt
HAVINGCOUNT(*) >= @NumOfCallsHas anyone else experienced this?


Peter Larsson
Helsingborg, Sweden

View 9 Replies View Related

Uniqueidentifier Causing Strange Execution Plan

Jul 20, 2005

Can anyone help me with this strange problem please?I have a stored procedure, with a parameter defined as auniqueidentifier. The procedure does a select with a number of joins,and filters within the Where clause using this parameter.(@orderHeader_iduniqueidentifier)SELECT*FROM originalOrderHeader oohINNER JOIN originalOrderLine oolON ooh.id = ool.idFULL OUTER JOIN orderLine olon ool.id = ol.idAND ool.productCode = ol.productCodewhere (ooh.id = @orderHeader_id)There is a clustered index on the id column of originalOrderHeader,and on id and productCode of both originalOrderLine and orderLine.These indexes are regularly rebuilt. The execution plan shows a seekagainst these indexes, but the estimated row count values are huge,and should be single figures.If I change the SP to accept the parameter as a varchar, and thenexplictly cast back to a uniqueidentifier in the where clause, the SPruns much, much quicker, the execution plan is doing far less work,and crucially the estimated row counts on the clustered index seeksare correct (single figures).Does anyone have any ideas what might be causing this?

View 1 Replies View Related

SQL Server 2008 :: Is Only One Plan Is Kept For One Query In Plan Cache

Mar 14, 2015

Is only one plan is kept for one query in plan cache?

i heard generally hash is created for a query and plan is search with this hash.

View 2 Replies View Related

Master Data Services :: Error - Query Processor Could Not Produce A Query Plan

Jul 19, 2015

We have a issue with a MDS server that have been over us for a couple of days, the original error msg from SQL Server Engine is the one "The query processor could not produce a query plan" but the ones we get on the Excel-Addin are "Sequece contains no elements" or "The value cannot be null" T

• Using Microsoft SQL Server 2012 (SP1) - 11.0.3393.0 (X64) for 6months on this server without issues

• Two weeks ago we started to have 2 errors: "Sequence Contains No Elements" | "The Value Cannot Be Null"

• We are using the last version of Excel Add-in

• We try to reinstall the MDS feature

• If I backup/restore MDS database to other server it works

• We updated to SQL 2012 SP2 + CU4 but the error persisted ...

Looking at the MDSTraceLog we are routed to the this msg

SQL Error Debug Info: Number: 8624, Message: Internal Query Processor Error: The query processor could not produce a query plan. For more information, contact Customer Support Services., Server: bbdvsql03inst01, Proc: udpMetadataEntityGetDetailsXML, Line: 28

At line 28 udpMetadataEntityGetDetailsXML is calling udfMetadataEntityGetDetailsXML … and here is where we stopped

** Error found when try to get data from a entity using Excel add-in **
===================================
Sequence contains no elements
------------------------------
Program Location:
   at Microsoft.MasterDataServices.AsyncEssentials.AsyncResultBase.EndInvoke()
   at Microsoft.MasterDataServices.ExcelAddInCore.AsyncProviderBase`1.EndOperation(IAsyncResult ar)

[code]....

View 3 Replies View Related

DB Engine :: Multiple Execution Of Query Pattern Generates Same Query Plan

Oct 6, 2015

SQL Server 2012 Performance Dashboard Main advices me this:

Since the application is from a vendor and I have no control over its code, how can improve this sitation?

View 3 Replies View Related

SQL Server Admin 2014 :: Estimated Query Plan For A Stored Procedure With Multiple Query Statements

Oct 30, 2015

When viewing an estimated query plan for a stored procedure with multiple query statements, two things stand out to me and I wanted to get confirmation if I'm correct.

1. Under <ParameterList><ColumnReference... does the xml attribute "ParameterCompiledValue" represent the value used when the query plan was generated?

<ParameterList>
<ColumnReference Column="@Measure" ParameterCompiledValue="'all'" />
</ParameterList>
</QueryPlan>
</StmtSimple>

2. Does each query statement that makes up the execution plan for the stored procedure have it's own execution plan? And meaning the stored procedure is made up of multiple query plans that could have been generated at a different time to another part of that stored procedure?

View 0 Replies View Related

SQL 2005 V9.0.2047 (SP1) - The Query Processor Could Not Produce A Query Plan

May 15, 2006

Hi Everyone:

*Before* I actually call up Microsoft SQL Customer Support Services and ask them, I wanted to ping other people to see if you have ever ran into this exact error

"Internal Query Processor Error: The query processor could not produce a query plan. For more information, contact Customer Support Services."

I would have searched the forums myself, but at this moment in time, search is broken :(

If anyone has run into this error before, what conditions would exist that this could happen? That is, if I can sniff this out with suggestions from the community, I would be happy to do so.

It is an oddity because if I alter a couple subqueries in the where clause [ i.e., where tab.Col = (select val from tab2 where id='122') ]to not have subqueries [hand coded values], then the t-sql result is fine. It's not as if subqueries are oddities... I've used them when appropriate.

fwiw - Not a newbie t-sql guy. ISV working almost daily with t-sql since MS SQL 2000. I have never seen this message before...at least I don't recall ever seeing it.

Thanks in advance for other suggested examination paths.

View 10 Replies View Related

Transact SQL :: Query Plan Shows Table Not Even In Query?

Jul 22, 2015

I am trying to optimize a stored procedure in SQL 2008.  When I look at an actual execution plan generated from when I run it in SSMS it shows a table being used in the plan that has no relation to what is actually in the query script and this is where the biggest performance hit occurs.

I've never seen a table show up before that wasn't part of the query. why this might occur and how to correct it?  I can't just change the query script because the table in question isn't there.

View 10 Replies View Related

Strange In Query

Jul 9, 2005

I have a query as follow:
SELECT @resRate = (SELECT resRate FROM ProjectAssign WHERE proNo =                                                             (SELECT projNo FROM Timer_Cust WHERE refNum = @actProjNo  AND                                                                        username= (SELECT username FROM Timer_Emp WHERE refNum = @actEmployee)                                                             )                                        )
 the definition of table Timer_cust contains refNum(int),  projNo(varchar) and projName(varchar).Timer_cust table doesn't contain column username. So  this query shoud generate a runtime error. however it works fine without error.But if I run                      SELECT projNo FROM Timer_Cust WHERE refNum = @actProjNo  AND                                                                        username= (SELECT username FROM Timer_Emp WHERE refNum = @actEmployee)A runtime error message appears.Why?

View 3 Replies View Related

A Strange Query

Jun 8, 2007

hi there , i'm using sql server 2005 express and i have some problems with the two of my tables :), iwant to query both of my tables but the table entries are not in an equal count of rows for example:

incoming(table) outgoing(table)

money date corp money date corp
15 1,1,2006 ar 17 1,1,2006 ar
25 1,2,2007 ar 21 2,2,2007 es
35 2,2,2007 es
6 3,3,2007 ar


in this example the first table has more rows but the opposite is possible in my tables because this is an (account extract) query and here's my problem: first i used the "select incoming.money as m1,incoming date as d1,incoming.corp as c1,outgoing.money as m2,outgoing.date as d2,outgoing.corp as c2 from incoming left outer join outgoing on incoming.corp=outgoing.corp where incoming.corp='ar'(or don't use the where eliminating)" any way i couldn't get the correct results, then i used the (union all) select , the result was ok but the results form is not what i want here's the form i want and is it possible to query to tables to get this?
in this query i just wanted the elements with the corporation named 'ar' for example:


m1 m2 d1 d2 c1 c2

15 17 1,1,2006 1,1,2006 ar ar
25 null(or (0)) 1,2,2007
6 null(or (0)) 3,3,2007


is it possible to achieve this form(and may be any of the tables may have more rows than the other, it's not exact) , i am in a very difficult position :) and now i need your help , thanks anybody to think of helping me

View 4 Replies View Related

STRANGE SQL Query

May 17, 2006

When I try to execute the below query:

select * from jobmaster where status in ('Active') and materialtypecode in (1,2) and unit='IMPERIAL' and superusercode='S051000014' order by controllercode,jobname

through ADO I got the error message:

Invalid column name controllercode

When I execute the same above query in MS SQL Query Analyzer it is working.

Is there any workaround?





View 3 Replies View Related

A Simple Strange Query..........

Mar 7, 2007

I am having in writing a simple select command........here's My ProblemI am using the ASP SQLDataSources in VS2005.... and my need is that i need to show Products details in a Gridview...... Actually through QueryString a StoreID is being fetched..... and the Products under those StoreID are shown..... if there is nothing in query string then it should show all the results... ........ It means that my querystring should be something like thisselect * from tblProducts where StoreID = <xyz>and <xyz> should be some thing that could show all the rows in that table ........ i mean that it should show all the possible results that can be shown through...select * from tblProducts

View 6 Replies View Related

Strange Problem W/ SQL Query

Jun 24, 2004

Okay... here's the deal...

I have two pages that Im using the same query out of... one page returns results, the other page returns an error... SOMEBODY HELP!!! I just need a hint if nothing more!!!

The Error:
System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'WHERE'.
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream)
at System.Data.SqlClient.SqlCommand.ExecuteReader()
at Global.Default_Search(Object Sender, EventArgs e) in C:InetpubwwwrootChampionRealtyINFOprojecttrackingglobal.vb:line 206

The SQL Query:

SELECT PT_JobCat.JobCat, PT_Job.JobID, PT_Job.Created, PT_Status.Status,
Offices.Name, Employees.First + ' ' + Employees.Last AS EmpName
FROM PT_Job
INNER JOIN PT_JobCat ON PT_Job.CatID = PT_JobCat.CatID
INNER JOIN PT_Status ON PT_Job.StatusID = PT_Status.StatusID
INNER JOIN PT_Assign ON PT_Job.JobID = PT_Assign.JobID
INNER JOIN Employees ON PT_Assign.AgentID = Employees.ID
INNER JOIN PT_Office ON PT_Job.JobID = PT_Office.JobID
INNER JOIN Offices ON PT_Office.Office_ID = Offices.ID
WHERE PT_Job.JobID=1


The SQL Query Output By ASP.NET: (When an error is produced on the trouble page)

SELECT PT_JobCat.JobCat, PT_Job.JobID, PT_Job.Created, PT_Status.Status,
Offices.Name AS OfficeName, Employees.First + ' ' + Employees.Last AS EmpName
FROM PT_Job
INNER JOIN PT_JobCat ON PT_Job.CatID = PT_JobCat.CatID
INNER JOIN PT_Status ON PT_Job.StatusID = PT_Status.StatusID
INNER JOIN PT_Assign ON PT_Job.JobID = PT_Assign.JobID
INNER JOIN Employees ON PT_Assign.AgentID = Employees.ID
INNER JOIN PT_Office ON PT_Job.JobID = PT_Office.JobID
INNER JOIN Offices ON PT_Office.Office_ID = Offices.ID
WHERE JobID=1


The Trouble Page:

Public Sub Default_Search(ByVal Sender As Object, ByVal e As EventArgs)
dim NeedAnd as boolean = False
dim strSQL as string = "SELECT PT_JobCat.JobCat, PT_Job.JobID, PT_Job.Created, PT_Status.Status, " & _
"Offices.Name AS OfficeName, Employees.First + ' ' + Employees.Last AS EmpName " & _
"FROM PT_Job " & _
"INNER JOIN PT_JobCat ON PT_Job.CatID = PT_JobCat.CatID " & _
"INNER JOIN PT_Status ON PT_Job.StatusID = PT_Status.StatusID " & _
"INNER JOIN PT_Assign ON PT_Job.JobID = PT_Assign.JobID " & _
"INNER JOIN Employees ON PT_Assign.AgentID = Employees.ID " & _
"INNER JOIN PT_Office ON PT_Job.JobID = PT_Office.JobID " & _
"INNER JOIN Offices ON PT_Office.Office_ID = Offices.ID " & _
"WHERE "
dim C as New SQLCommand(strSQL, Conn)
dim DR as SQLDataReader
If txtJobNum.Text <> Nothing Then
strSQL += "JobID=" & CInt(txtJobNum.Text) & " "
NeedAnd = True
End If
If ddlJobType.SelectedItem.Value <> Nothing Then
If NeedAnd Then strSQL += "AND "
strSQL += "CatID=" & ddlJobType.SelectedItem.Value & " "
NeedAnd = True
End If
If txtCreated.Text <> Nothing Then
If NeedAnd Then strSQL += "AND "
strSQL += "PT_Job.Created LIKE '" & txtCreated.Text & "' "
NeedAnd = True
End If
If ddlStatus.SelectedItem.Value <> Nothing Then
If NeedAnd Then strSQL += "AND "
strSQL += "PT_Job.Status=" & ddlStatus.SelectedItem.Value & " "
NeedAnd = True
End If
If ddlAssign.SelectedItem.Value <> Nothing Then
If NeedAnd Then strSQL += "AND "
strSQL += "Employees.ID=" & ddlAssign.SelectedItem.Value & " "
NeedAnd = True
End If
If ddlOffice.SelectedItem.Value <> Nothing Then
If NeedAnd Then strSQL += "AND "
strSQL += "Offices.ID=" & ddlOffice.SelectedItem.Value & " "
NeedAnd = True
End If

response.write(strSQL)

Conn.Open
Try
DR = C.ExecuteReader
If DR.Read Then
rptResults.Datasource = DR
rptResults.Databind
End If
DR.Close
Catch Exc as Exception
'ErrorAlert(Exc, strSQL)
response.write("<p>" & Exc.ToString.Replace(Environment.NewLine(), "<br />") & "</p>")
End Try
Conn.Close

End Sub


The Page That Works:

Sub LoadResults(ByVal Sender As Object, ByVal e As EventArgs)

' Clean up some things...
txtError.Visible = False
txtError.Text = Nothing

' Create database interaction objects...
dim Conn as Object
dim C as Object
dim DR

' Set database interaction objects...
Select Case CInt(DBType.SelectedItem.Value)
Case 0
Conn = New SQLConnection(txtConnString.Text)
C = New SQLCommand(txtSQL.Text, Conn)
Case 1
Conn = New OleDbConnection(txtConnString.Text)
C = New OleDbCommand(txtSQL.Text, Conn)
Case Else
txtError.Visible = True
txtError.Text = "Whoa... wierd error d00d... o.0"
End Select

' Open the database for reading...
Conn.Open

Try

' Load the datagrid with any information retrieved...
Select Case CInt(CommType.SelectedItem.Value)
Case 0
DR = C.ExecuteReader()
dgResults.Datasource = DR
dgResults.Databind
DR.Close
Case 1
C.ExecuteNonQuery()
Case Else
txtError.Visible = True
txtError.Text = "That's some funky ****..."
End Select

Catch Exc As Exception

' Make the error viewable so we know what went on...
txtError.Visible = True
txtError.Text = Exc.ToString

End Try

' Close the connection to the database...
Conn.Close

End Sub

View 7 Replies View Related

Strange Query Behaviour

Aug 12, 2000

Hi...

Not sure what's wrong with the query or table, but I just can't get the result I want.

The column is varchar(35) and contains toll free no, like 18001234567...

But when I queried using the query below, I can't get any results. Same if I use 1*, 18*, 180*...

SELECT ... FROM ...
WHERE CONTAINS(toll_no, '"1800*"')

However, if I used 18001* I do get results.
Can anybody show me how to get result for these cases?

Thanks.

View 2 Replies View Related

Strange Query Needed

Apr 25, 2007

Hi Friends,

I need a very strange SQL query.
I have table structure like

cat_id, cat_name, cat_parent_id

Each cat has subcategories and those subcategories can have subcategories means

1, Cat1, 0
2, Cat2, 0
3, Cat3, 2
4, Cat4, 2
5, Cat5, 4

So Cat1 >> Cat2 >> Cat3

Now , I need a list of cat, subcat and subcat's subcat in a single query. e.g.
If I need all subcat of cat 2 then
result should be

2,3,4,5

Is it possible in a single query?
thanks.

View 3 Replies View Related

Strange SQL Query Problem

Jan 18, 2006

Good Morning!

First off, let me get my disclaimer out of the way - I'm a relative newbie at this SQL lark, so please ignore the kludgy-ness of this code etc. Thanks ;-)

Firstly, here's my query:


Code:



SET DATEFORMAT DMY

declare @issuecounter int; -- Declare
declare @previssue int; -- Declare
declare @date smalldatetime -- Declare

DECLARE @issues TABLE (issues int, dates smalldatetime)
-- Declare

DECLARE issue Cursor scroll FOR -- Create the cursor
select articleIssue, articleDate from cr_newsletterArticles
where newsletter = @newsletter -- Which Newsletter
order by articleIssue desc ;

open issue -- Open the cursor
SET @previssue = 0 -- Set our comparison variable to 0

FETCH next FROM issue -- Grab the first recordset from the cursor
into @issuecounter, @date -- Stick it into our variable
WHILE @@fetch_status = 0 -- While we're not at EOF
begin -- begin
if @issuecounter != @previssue BEGIN -- begin
insert into @issues(issues,dates)
values(@issuecounter, @date)
SET @previssue = @issuecounter -- set comparison variable to issuecounter
END
fetch next from issue -- Grab the next recordset
into @issuecounter, @date
END -- End
CLOSE issue -- close cursor
deallocate issue
select * from @issues
GO



When I run this query in Query Analyser, it seems to work fine. IE. I get a table returned with the correct values. However, when I try and get this data into ASP via the old objRS.open "EXECUTE stored procedure <value>" command, no data is returned...

I'm not sure if this is an ASP problem, or a SQL problem... So, I altered the query slightly, and instead of a temporary table, I used a static one in the database, and it still didn't work - even though when I open the table in Enterprise manager the content is there...

Also, if I run the query via an ASP objCommand.execute "procedure <value> " and then use objRS.open "SELECT * from table" then it pulls the data in properly then...

If I was dealing with millions of recordsets in my original table, then I can understand that maybe the ASP isn't waiting long enough for SQL to return its final table. But I'm currently only dealing with about 50... I'd rather use the temporary table route rather than static incase of multiple hits at the procedure at the same time...

Any ideas? Please go easy - I refer you back to my disclaimer ;-)

Thanks...

View 2 Replies View Related

Strange Results From Not In Query

Jul 10, 2006

Hi all,Using SQL Server 2000, SP4.I have a table of street names (Rua) whose ids (cod_rua) are foreignkeys into a consumer table (Consumidor). It turns out that the "Rua"table has many unused records which I'd like to wipe out. For instance,there are some 2800 unused records in the "Rua" table, and only some200 records actually being used by the "Consumidor" table (which,itself, has some 5000 records).Attempting to find the unused records, I issued the following query:a)SELECT COD_RUA FROM RUAWHERE COD_RUA NOT IN (SELECT COD_RUA FROM CONSUMIDOR)To my surprise, the query came out empty. But the following queryshowed the 200 or so records which *are* being used:b)SELECT COD_RUA FROM RUAWHERE COD_RUA IN (SELECT COD_RUA FROM CONSUMIDOR)I've found two solutions for the query to list the records *notexisting* in the Consumidor table:c)SELECT COD_RUA FROM RUAWHERE COD_RUA NOT IN (SELECT COD_RUA FROM CONSUMIDORWHERE COD_RUA IS NOT NULL)d)SELECT COD_RUA FROM RUAWHERE COD_RUA NOT IN (SELECT COD_RUA FROM RUAWHERE COD_RUA IN (SELECT COD_RUA FROM CONSUMIDOR))I know that there are many other possible solutions to the query(including left joins), but what I don't understand is why the query a)failed.Can some of you, oh mighty gurus, enlighten me?For the record, here's how both tables are (partially) declared:CREATE TABLE Rua (Cod_Rua int NOT NULL ,Rua varchar (35) NULL ,-- ...-- other unrelated fields-- ...CONSTRAINT Pk_CodRuaPRIMARY KEY (Cod_Rua))CREATE TABLE Consumidor (Cod_Consumidor int NOT NULL ,Cod_Rua int NULL ,-- ...-- other unrelated fields-- ...CONSTRAINT Pk_CodConsumidorPRIMARY KEY(Cod_Consumidor) ,CONSTRAINT Fk_CodRua_ConsumidorFOREIGN KEY (Cod_Rua)REFERENCES Rua (Cod_Rua))Regards,Branco Medeiros

View 3 Replies View Related

Strange Query Timeout

Jul 20, 2005

Hi everibody,it's the first time i post on this newsgroup. I'm Stefano from Milano,italy.I'm a beginners with Sql2000. My problem is this.I run a View using enterprise manager and after less then 20 second it goesin error time out. I run this view using a VB application and the errorcomes again .When i run it with Query Analyzer after 50 seconds it give methe right result.i've tried to change the value of querytimeout using sp_configure with thesame bad result.i've tried to change the ado command timeout in visul basic but stilldoesn't work.any suggest ?Thanks in advance

View 4 Replies View Related

Strange Slow Query

Mar 26, 2007

Hi all,

Last week we've made some modifications to our 20 GB database(with 2 huge tables (around 30 million rows)):
1.
we've created 8 filegroups on 8 physical disks with RAID 1+0. In each
of them we have one big table and others small tables unrelated with
the big table. We've also created a filegroup for the nonclustered
indexes from those big tables.
2. The Server is running SQL Server 2000 with SP3a
3. We've reindexed the database, updated statistics on all tables
Now, we have a SP that on the old configuration took about 20 min to complete.
But now, on our new configuration with the modifications listed above it's taking about
3 HOURS.
This is the SP's body: is calling a function:
create proc X
as
begin
Select dbo.myfunc(mytable.field)
from mytable
end

The function used in select statement is querying those 2 huge tables.

If the select statement is runned for only one record it's done instantly, but for 20000 recs it is taking almost 3 hours.
I must specify that also the function is running instantly, but in that select statement something is happening and we don't know what!!!

If you have any ideeas on what to do or what to check
Thanks a lot
Dan

View 5 Replies View Related

Strange Query Behaviour

Nov 15, 2006

Hi,

I am seeming strange results with a query. I have two tables, lets call them Table1 and Table2. Table1 has an ID field, Table2 does not have an ID field. To be sure I wasn't blind, the query

'SELECT ID FROM Table2'

returns: Invalid column name 'ID'. OK. Now when I run the query

'SELECT * FROM Table1 WHERE ID IN (SELECT ID FROM Table2)'

it returns all the records from Table1.

What gives? Is this a bug, or am I missing something?

View 8 Replies View Related

Strange Query Performance Issue

Nov 23, 2006

Jezemine,
No, the number of reads is approximately the same. I can also confirm the disk read speed is the same on the test vs. production server. Update stats is run regularly on the production server - as I test, I ran sp_updatestats and then immediately ran the query a few times but it didn't affect the duration. Apart from the durations in the profiler traces, I can't see any differences. Clearly, something is causing the increased duration on the prod server but I don't know where to look to find it. It's definitely within SQL Server 2000.

Clive

View 8 Replies View Related

Query Plan

Jul 23, 2002

I am noticing a discrepency in query plans when a process is run in Analyzer as either a proc or as straight sql.

I have a query that uses a view of 5 tables that have a check constraint on the year. When I run my query in query analyzer and state year = 1999 along with over parameters then the query plan only looks at the one table.

When I take that query and make a stored proc and run the process passing the year = 1999 along with other parameters the plan states that it is looking at all of the tables in the partitioned view.

Thanks,

Here is a copy of the proc


create procedure testproc
@CUST_I varchar(6),
@FISCAL_DD_D tinyint,
@FISCAL_MM_D tinyint,
@FISCAL_YY_D smallint,
@cont_cvarchar(1),
@invoice varchar(9)
as
Select
CONT_C,
INVC_I,
DIV_C,
REG_C,
LOC_I,
INVC_D,
CUST_I,
CR_PREF_C,
FISCAL_DD_D,
FISCAL_MM_D,
FISCAL_YY_D,
PAY_CODE,
REF_TEXT,
EC_TYPE,
ADJUST_A,
ALLOWANCE_A,
MAT_A,
TAX_A,
FRT_A,
REEL_A,
OTHER_A,
GST_A,
PRIOR_BAL

from MY_FIVE_YEAR_VIEW

whereFISCAL_YY_D = @FISCAL_YY_D
AND cont_c = @cont_c
AND FISCAL_DD_D = @FISCAL_DD_D
AND FISCAL_MM_D = @FISCAL_MM_D


AND (REF_TEXT LIKE '%' + @CUST_I + '%' or REF_TEXT LIKE '%' + @invoice + '%' )


order by cust_i, pay_code

View 1 Replies View Related

A Strange Problem With SQL Query Fro Getting Field Names

Aug 9, 2004

Hello All,

I have been trying to get this code work, but I could not. Every thing seems going well. However, The result of running the sql query is strange. It shows the field names twice.
Eg:) if you have a table called "newtable" that has two fields[Custnumber, Custname], you will get somthing like this [Custnumber, Custname Custnumber, Custname]. I have tried many times, but I couldn't fix it.



Sub Page_Load(sender As Object, e As EventArgs) handles Mybase.Load

if not page.Ispostback then

try
Sqlconnection = New Sqlconnection (connectionString)

querystring = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNs
WHERE TABLE_NAME = 'Newtable'"

SqlCommand = New SqlCommand(queryString, Sqlconnection)

SqlConnection.Open

dataReader = SqlCommand.ExecuteReader(CommandBehavior.CloseConnection)


while dataReader.Read()

Tablefields_txt.text += dataReader.Getstring(0) & ", "


End while

catch ex as Exception


msgbox("An error has occured: " + ex.Message,0, "Error Message")

finally


SqlConnection.Close()


End try
End if



Any help , please

View 3 Replies View Related

Strange Query Analyzer Decision - Question

Mar 20, 2001

We have SQL server 7 installed. And we experiencing the performance problem.
When I tried to solve this problem I have found the interesting thing:
We have the table S_EVT_ACT with the non clustered index
S_EVT_ACT_F4 created on [OWNER_PER_ID], [APPT_REPT_FLG] fields and another clustered one
S_EVT_ACT_M4 created on [ROW_STATUS], [OWNER_PER_ID] fields
I use the next select statement and before run this statement I declare the variable @P1 - @P5 and set the values to them:

declare @P1 as char(1)
declare @P2 as char(1)
declare @P3 as char(1)
declare @P4 as varchar(10)
declare @P5 as char(1)

set @P1 = 'Y'
set @P2 = 'Y'
set @P3 = 'N'
set @P4 = '1-K56'
set @P5 = 'Y'

SELECT
..
...
...
FROM
dbo.S_EVT_ACT T1 --(index = S_EVT_ACT_F4)
LEFT OUTER JOIN dbo.S_CONTACT T2 ON T1.TARGET_PER_ID = T2.ROW_ID
LEFT OUTER JOIN dbo.S_OPTY T3 ON T1.OPTY_ID = T3.ROW_ID
LEFT OUTER JOIN dbo.S_ORG_EXT T4 ON T1.TARGET_OU_ID = T4.ROW_ID
LEFT OUTER JOIN dbo.S_EVT_ACT_X T5 ON T1.ROW_ID = T5.PAR_ROW_ID
WHERE
((T1.ALARM_FLAG = @P1 OR T1.APPT_REPT_REPL_CD IS NOT NULL) AND
(T1.APPT_REPT_FLG = @P2 AND (T1.CAL_DISP_FLG = @P3 OR T1.CAL_DISP_FLG IS NULL)) AND
(T1.OWNER_PER_ID = @P4) AND
(T1.TEMPLATE_FLG != @P5 OR T1.TEMPLATE_FLG IS NULL))
ORDER BY
T1.CREATED

In this case Query Analyzer uses S_EVT_ACT_M4 index and the performance is bad!

But when I try to run the same statement and use hard code 'Y' instead of the variable @P2 the Query Analyzer uses the S_EVT_ACT_F4 index and performance is PERFECT.

Question: What the difference between using variable @P2 and hard code 'Y' in the select statement and how to configure SQL server to use the right index in the situation when I can't change the Select statement and use the hard coding?

Any Idea will be very Appreciated.

Dmitri Denejkine
stssystems
MS SQL Server DBA, MIS
(514) 426-0822 ext. 2676

View 3 Replies View Related

Simple Query Causing Strange Problem.

Feb 11, 2004

declare @l decimal(38,2)
select @l = 24.35

if @l - convert(int,@l) = 0
select floor (@l)
else
select @l

select case
when @l - convert(int, @l) = 0 then floor (@l)
else @l
end

The if statement is giving correct result, but the case statement is not. I am fed up why it is so. Please advise.

View 14 Replies View Related

SQL 6.5 Query Execution Plan .

Sep 24, 2002

Hello ,

I wanted to know whether we have an execution plan enabled in SQL 6.5 as we have it in SQL 7.0 and SQL 2000 .
I.e when we execute a query and if we enable ' show execution plan 'then it creates a map and shows the vital statistics .
If that is available on SQL 6.5 then i am missing that tool .

How can i have it installed on my SQL 6.5 server ??

Thanks.

View 3 Replies View Related

Query Plan Re-use On Views?

Apr 25, 2006

Here's the setup:

Client database has a complex view with eight nested subqueries used to return "dashboard" information. The application code uses NHibernate to call and filter the view with three parameters, one of which is the CustomerID.

A certain customer, (the biggest client), has more than ten times the number of records of the next largest customer.

Occasionally, the database reaches a state where when this particular customer tries to run the dashboard view, the application times out.

If I open up the view and re-save it, all is well again for a few days.

What gives?

Views are supposedly not pre-compiled, though I know that 2000 stores bits and pieces of query plans.

Any ideas on what causes this and what to do about it?

View 2 Replies View Related

Saving Query Plan

Sep 13, 2005

I would like to save a query plan (estimated or actual)created in Query Analyzer -- paste it into a document,or simply print. It doesn't seem to be possible toselect and copy the Execution Plan window, and printingit creates microscopic gibberish which is a waste ofpaper. Is it possible to do this?Set showplan_text is of limited help for the SP I'mlooking at -- while analyzing the SP, it reads aheadand complains that a temp table created inside the SPdoesn't exist (yet) and exits. Using Ctrl-K to capturethe query plan allows the SP to complete, but saving theplan is the problem.Thanks,Jim Geissman

View 2 Replies View Related

Odd Query Plan For View

Mar 28, 2006

I have a SQL 2000 table containing 2 million rows of Trade data. Hereare some of the columns:[TradeId] INT IDENTITY(1,1) -- PK, non-clustered[LoadDate] DATETIME -- clustered index[TradeDate] DATETIME -- non-clustered index[Symbol] VARCHAR(10)[Account] VARCHAR(10)[Position] INTetc..I have a view which performs a join against a security master table (togather more security data). The purpose of the view is to return allthe rows where [TradeDate] is within the last trading days.The query against the view takes over around 30 minutes. When I viewthe query plan, it is not using the index on the [TradeDate] column butis instead using the clustered index on the [LoadDate] column... Theodd thing is, the [LoadDate] column is not used anywhere in the view!For testing purposes, I decided to do a straight SELECT against thetable (minus the joins) and that one ALSO uses the clustered index scanagainst a column not referenced anywhere in the query.There is a reason why I have not posted my WHERE clause until now. Thereason is that I am doing what I think is a very inefficient clause:WHERE [TradeDate] >= fGetTradeDateFromThreeDaysAgo(GetDate())The function calculates the proper trade date based on the specifieddate (in this case, the current date). It is my understanding that thefunction will be called for all rows. (Which COULD explain theperformance issue...)However, this view has been around for ages and never before caused anysort of problems. The issue actually started the day after I had torecreate the table. (I had to recreate the table because some columnswhere added and others where renamed.)On a side note, if I replace the WHERE clause with a hard-coded date(as in 'WHERE [TradeDate] >= '20060324'), the query performs fine butSTILL uses the clustered index on the [LoadDate] column.

View 4 Replies View Related

Puzzled By Query Plan

Jul 20, 2005

I'm hoping somebody can explain exactly what's going on here - I can'tfind it documented anywhere.Go to the Northwind database, and run the following SQL:create index IX_UnitPrice on [order details](unitprice)Now, turn on SHOWPLAN (either graphical or text, it doesn't matter),and run the following query:select * from [order details]where unitprice = 2Output:StmtText|--Index Seek(OBJECT: ([Northwind].[dbo].[OrderDetails].[IX_UnitPrice]), SEEK: ([OrderDetails].[UnitPrice]=Convert([@1])) ORDERED FORWARD)Now, alter the SARG slightly by making it a float:select unitprice from [order details]where unitprice = 2.000Output:StmtText|--Nested Loops(Inner Join, OUTER REFERENCES: ([Expr1003], [Expr1004],[Expr1005]))|--Compute Scalar(DEFINE: ([Expr1003]=Convert(Convert([@1]))-1.00,[Expr1004]=Convert(Convert([@1]))+1.00, [Expr1005]=If(Convert(Convert([@1]))-1.00=NULL) then 0 else 6|If(Convert(Convert([@1]))+1.00=NULL) then 0 else 10))| |--Constant Scan|--Index Seek(OBJECT: ([Northwind].[dbo].[OrderDetails].[IX_UnitPrice]), SEEK: ([Order Details].[UnitPrice] >[Expr1003] AND [Order Details].[UnitPrice] < [Expr1004]), WHERE:(Convert([Order Details].[UnitPrice])=Convert([@1])) ORDERED FORWARD)Right. I understand that in both cases the SARG datatype is differentfrom the column datatype (which is money), and that in the firstexample the SARG constant gets implicitly converted from int -> money(following the datatype hierarchy rules), and so the index can stillbe used.In the second example, the datatype hierarchy dictates that money islower than float, so the table column gets implicitly converted frommoney -> float, which strictly speaking disallows the use of the indexon that column.What I DON'T understand is what exactly all that gubbins about theexpressions (especially the definition of [Expr1005] is all about; howdoes that statement decide whether Expr1005 is going to be NULL, 6, or10?I'm soon going to be giving some worked tutorials on index selectionand use of Showplan to our developers, and being a bolshi lot they'rebound to want to know exactly what all that output means. I'd ratherbe able to tell them than to say I don't actually know!How about it someone?Thanks,Phil

View 4 Replies View Related

Synonym And Query Plan

Oct 23, 2006

I may just be completely missing something here but, when I view a query plan from a SQL statment that involves a join with a synonym I do not see any reference to the synonym or the underlying table referenced by it in the query plan? Any thoughts?

Thx!

View 5 Replies View Related

Incorrect Query Plan

Nov 16, 2007

I was doing a demo last night, something that I've done hundreds of times already. Last night was the first time that it has failed to work. I was trying to show what the sys.dm_db_missing_index_* DMVs can provide.

AdventureWorks database

I'm running the following query:

select city from person.address where city like 'A%'


This is supposed to produce a table scan which in turn will obviously cause SQL Server to detect that an index could be beneficial. However, it does a clustered index scan (yes, I know, basically the same thing) instead and I see absolutely nothing appear in the DMVs. I pulled the data out into a dummy table that did not have a primary key either using the following:
select * into person.tmpaddress from person.address

I then execute the same query and get a table scan which is expected:

select city from person.address where city like 'A%'

However, it does not matter how much I execute that query or any other permutation of explicit query, absolutely nothing at all gets logged into the sys.dm_db_missing_index_* DMVs. I have also tried this same type of thing with several other tables in the AW database and can not find a single query which will cause anything to be logged to these DMVs. It seems that something is broken, but for the life of me, I can't figure out what is wrong. No weird settings, I'm running as sa, etc.


I can run queries like this in other databases and stuff gets immediately logged to the DMVs as expected. Any ideas?

View 5 Replies View Related







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