Speed Cost For Using Or Clause And Functions On Join Statement
Jul 23, 2005
Select member
from NameList
Inner join Members
on (Left(Namelist.NameID,5) = Members.ID
OR (left(namelist.SSN,9) = Members.ssn
OR (Left(namelist.CustID,9) + '*01' = Members.CustID)
where
namelist.name <> ''
How do I speed up a process like this? Can I create indexes on the
members table based on a function
Like an index based on the left(members.id,5)
or should these statements go into the where clause?
I need to expand resursion level for resursive CTE expression within CREATE FUNCTION statement for inline table function to a value greater than default. It turns out that OPTION clause for MAXRECURSION hint perfectly works if I use it outside CREATE FUNCTION (as well as CREATE VIEW for non-parametrized queries), but it does not within CREATE FUNCTION statement - I'm getting error:
Msg 156, Level 15, State 1, Procedure ExpandedCTE, Line 34
Incorrect syntax near the keyword 'option'.
Here is the function:
create FUNCTION [dbo].[ExpandedCTE]
(
@p_id int
)
RETURNS TABLE
AS
RETURN
(
with tbl_cte (id, tbl_id, lvl)
as
(
select
id, tbl_id, 0 lvl
from
tbl
where
id = @p_id
union all
select
t.id, t.tbl_id, lvl + 1 from
tbl_cte inner join tbl t
on rnr.tbl_id = tbl_cte.id
)
select
id, tbl_id, lvl
from
tbl_cte
option (maxrecursion 0)
)
Please help!
Alexander.
P.S. I'm really sorry if it is about syntax, but I could not find it in the documentation.
Hi, I'm trying to inner join an update statement. Something like this:
update #point_connection_temp AS a inner join #point_connection_temp_two as b on a.key_fld = b.key_fld set a.next_point = b.next_point where #point_connection_temp.next_point is null order by a.key_fld
I'm getting an error message:Incorrect syntax error near AS Any help will be greatly appreciated.Thank you!!!!!!!!!1
I need to write a SQL script where a join condition is using date columns (effective_date, ineffective_date). The effective date columns can be slightly different (e.g. differ by a day) for some rows of data. I need the join condition to accommodate these date differences and return these rows of data as well.
I have a table which uses multiple joins to create another table but it turns out that the effective_date which is used in the join to match row together does not work all the time since some of the dates for the effective date column are out of sync meaning records that show data as missing even when the other table contains the data. I tried the SQL script below using the BETWEEN clause but it returning 6 rows instead of 3–
I've a table similar to the one below, with a SKU, Category and Cost, and need using a simple select command, split the cost in two columns one for each category (1,2), I used a self-join, and it works, but it doesn't show values not equal in both categories
Declare @Tmp_SKUCatValue Table( SKU char(7) ,Cetegory Int ,Unit_cost Decimal ); INSERT INTO @Tmp_SKUCatValue (SKU, Cetegory,Unit_cost) Values ('sku-001',1,120)
1. Right now in my queries I am using lots of LEFT Joins and INNER JOINs... and I was suggested to look at 'IN'... But with IN I did face some performance issues previously and stopped using it... but I have got new doubts on which query will give me better performance...
A query using LEFTJoin or a query using IN/NOT-IN
2. This question is about CONVERT...
I have a stored proc which is used for updating a table... and multiple columns [of the same table] and corresponding values are sent to the proc [only a subset of the columns might be sent for updates everytime and the columns to update is not fixed for each run of the SP]...
I have to construct a UPDATE String out of it using string concatenation to finally be able to use "sys.sp_executesql" on that update statement...
This results in me having to use CONVERT() lots of times... and one of the columns among them on which I am doing a CONVERT is of the type XML...
So the question is as follows... a. Is it preferrable to construct a single UPDATE statement string and execute it using "sys.sp_executesql" b. Or Is it preferrable to give multiple UPDATE statments... i.e. one update statement for each column [Depending on whether that column has to be updated for that run or not]
i.e. The question essentially is:
Does a single update query constructed using lots of CONVERTS [Basically on INT and XML types] give more performance over using multiple UPDATE statments on the table Or is it the other way round..
I need to build TSQL query to return the Last unit Cost from my table of movement of goods SL (on CTE) but the MAX(Datalc) must be Less or Equal to my HeaderInvoice.
This is my script:
With MaxDates as ( SELECT ref, MAX(epcpond)[Unitcostprice], MAX(datalc) MaxDate FROM sl
[code]....
the problem I have right now is that the Unitcostprice of my table of goods movements has a top date greather than the date of my bill.
Example:
invoice date : 29.01.2015 unitcost on invoice line = 13,599722 Maxdate (CTE) : 19.03.2015 unitCost from my table of movement of goods = 14,075
That ´s not correct because the MAxdates > invoice date and the unitCost of 14,075 is the cost on 19.03.2015 and not just before my invoice date.
Edited by SomeNewKid. Please post code between <code> and </code> tags.
// Pls copy the following HTML after that you generate the HTML page. Then you will know what I mean. I need to form "New Table" from Job Revence and Job Cost using SQL statement? thx
I right in thinking that if the estimated subtree cost is higher than the cost threshold for parallelism then it will use a parallel plan? If so, I've read the cost threshold is measured in minutes but is the subtree cost measured in something else, the mysterious cost number? And if so, how are the two compared?
Is there any way of emulating Oracle's capability of passing output of user-defined functions in the select statement or better still in the Where clause in SQL server 7.0? If not then could we hope for it in SQl server 2000?
I am having trouble with a particular query that is beyond my scope of understanding.
Basically I need to pull sales records based on the following criteria:
I have CustomerID, InvoiceNumber, ContractEndDate, MobileNumber, etc..
Customers recontract their mobile phone plans through us, and we have a new sales record for each time they recontract.
For example, CustomerNumber 123 has recontracted 3 times..
once on 2006-01-01, then on 2007-02-12, and finally on 2008-02-15..
So they have a 12 month contract each time.. then come in to recontract it.
So.. a customer has a single Customer Detail record, but may have many sales records attached. And a customer may have several sales for the SAME mobile phone number.
Currently to pull ALL sales records for all customers, my query is this:
Code:
SELECT xxx.CustomerID AS xxx_CustomerID, xxx.Invoice AS xxx_Invoice, yyy.PhoneType AS yyy_PhoneType, yyy.PlanType AS yyy_PlanType, yyy.ContractEnds AS yyy_ContractEnds, yyy.MOB AS yyy_MobileNumber
FROM dbo.SaleControl xxx INNER JOIN dbo.SaleDetails yyy ON xxx.Invoice = yyy.Invoice
WHERE yyy.ContractEnds IS NOT NULL AND xxx.CustomerID IS NOT NULL
We want to get a list of customers that we can call to recontract, based on the ContractEnd field.
However, we want UNIQUE mobile phone numbers, with the LATEST ContrtactEnd date.
So, Customer 123 has 6 sales, for 2 unique Mobile numbers, the sql may be like:
Code:
SELECT MAX(yyy.ContractEnds) AS LatestCED, yyy.MOB FROM dbo.SaleControl xxx INNER JOIN dbo.SaleDetails yyy ON xxx.Invoice = yyy.Invoice WHERE xxx.CustomerID='123' GROUP BY yyy.MOB
Now, this works fine, and of course if i remove the WHERE clause, it collects all unique mobiles, with latest ContractEnd date for each, for all customers. (Customer 123 displays 2 mobile numbers, each with the LATEST ContractEnd date)
BUT i need this information ALONG WITH the other fields (xxx.CustomerID, xxx.Invoice, yyy.PhoneType, yyy.PlanType) and i have tried a few ways of doing it, but can't get my head around it..
Keep getting errors about Aggregate functions and Group By clause, and i understand why i am getting them, just cant think of any alternative query.
i have been trying to determine which is the most efficient, with regards to speed and efficiency, between a view and a common/nested table expression when used in a join.
i have a query which could be represented as index view or a common table expression, which will then be used to join against another table.
the indexed view will use indexes when performing the join. is there a way to make the common table expression faster than an indexed view?
The following stored procedure is run whenever someone searches my database. When I first created the site, this search took less than 3 seconds. Now, there is more data in the system and the search is taking over 30 seconds. I am not very good with SQL and I'm sure I am doing some dumb things. Is there a better way to write this query to speed things up? Thanks a lot, Chris MessineoSET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author:Chris Messineo -- Create date: 4/27/2007 -- Description:Get Search -- ============================================= ALTER PROCEDURE [dbo].[Search] @Keyword as varchar(40)=NULL AS BEGIN SELECT Script.Title, Script.ScriptID, Script.Logline, Member.Name FROM Script Join Contest on (Script.ContestID=Contest.ContestID) Join ScriptComment on (Script.ScriptID=ScriptComment.ScriptID) Join Member on (Script.MemberID=Member.MemberID) WHERE (Title like '%' + COALESCE(@Keyword, Title) + '%' or Logline like '%' + COALESCE(@Keyword, Logline) + '%' or Comments like '%' + COALESCE(@Keyword, Comments) + '%') GROUP BY Script.Title, Script.ScriptID, Script.Logline, Member.Name ORDER BY Title END
Background: I have a table (named achtransactions) that has 618,423 rows. I have the ID field set as the Primary Key.
Problem: Usually when doing a single, simple update (ie: UPDATE achtransactions SET transstatus = 'APPROVED' where id = 123456) it would take less than a second.
All of a sudden, beginning today, the same UPDATE statement is taking about 20 seconds on average. Other smaller tables (~100 rows) update instantly, just appears to be this one table.
Any ideas on what I should look at to find the problem?
The data I am pulling is correct I just cant figure out how to order by the last 8 numbers that is my NUMBER column. I tried adding FOR XML AUTO to my last line in my query: From AP_DETAIL_REG where AP_BATCH_ID = 1212 and NUMBER is not null order by NUMBER FOR XML AUTO) as Temp(DATA) where DATA is not null
but no change same error. Output: 1234567890000043321092513 00050020
Select DATA from( select '12345678'+ left( '0', 10-len(cast ( CONVERT(int,( INV_AMT *100)) as varchar))) + cast (CONVERT(int,(INV_AMT*100)) as varchar) + left('0',2-len(CAST (MONTH(DATE) as varchar(2))))+ CAST (MONTH(DATE) as varchar(2)) + left('0',2-len(CAST (day(CHECK_DATE) as varchar(2)))) + CAST (day(DATE) as varchar(2))+right(cast (year(DATE)
I am using web developer 2008, while connecting to I wanted to fetch data from Lotus notes database file, for this i used notesql connector, while connectiong to notes database i am fetting error
ERROR [42000] [Lotus][ODBC Lotus Notes]Table reference has to be a table name or an outer join escape clause in a FROM clause
I have already checked that database & table name are correct, please help me out How i can fetch the lotus notes data in my asp.net pages.
I am using web developer 2008, while connecting to I wanted to fetch data from Lotus notes database file, for this i used notesql connector, while connectiong to notes database i am fetting error
ERROR [42000] [Lotus][ODBC Lotus Notes]Table reference has to be a table name or an outer join escape clause in a FROM clause
I have already checked that database & table name are correct, please help me out How i can fetch the lotus notes data in my asp.net pages.
SELECT DISTINCT fcompany ,SUM(fnetprice) As "TotalPrice" ,MAX(CONVERT(DATE,fduedate)) AS "LastPurchase" FROM SalesHistory Group by fcompany
I would like to filter out of the results 2 things..
#1 I would like ONLY the results where "TotalPrice" > 1000 #2 I would like "LastPurchase" only to be the system sate -365 days (I know I can achieve that like This: CONVERT(DATE, fduedate) > dateadd(day,-365,getdate())
But neither of the 2 conditions I can add in a WHERE / AND clauses.
I'm having trouble with a multi-table JOIN statement with more than one JOIN statement.
For each order, I need to return the following: CarsID, CarModelName, MakeID, OrderDate, ProductName, Total ordered the Car Category.
The carid (primary key) and carmodelname belong to the Cars table. The makeid and orderdate belong to the OrderDetails table. The productname and carcategory belong to the Product table.
The number of rows returned should be the same as the number of rows in OrderDetails.
Hi everyone, I saw some queries where SQL inner join clause and the where clause is used at the same time. I knew that "on" is used instead of the "where" clause. Would anyone please exaplin me why both "where" and "on" clause is used in some sql Select queries ?
I have several data bases on a server (SQL Server 2000 only, no web server installed) and lately, as the company keeps gowing, my users complain saying the server gets slow, (this dbs are well designed and recieve optimizations and integrity checks, etc) because of this, Im thinking about getting a new server to repleace my old ProLiant ML 330 which was bought 4 years ago but Im concerned about what server arquitecture or characteristic can help me best to improve response performance, is it HD speed? Processor speed? or more Ram? I want to make a good decision, so I´d really appreciate your help...
I think I am getting 0 records returned... because.... I am joining the third value based on a zip code. The two tables if directly compared to each other would never have an = match. SELECT t2.company_name, t2.firstname, t2.lastname, modelname, configname, format, version, username, t2.zip,
t2.country FROM EtechModelRequests JOIN CC_Host.dbo.USR_SC as t2 ON Cast(t2.user_id As char) = username --JOIN --Sales.dbo.RF_Postal_Code_Salesman_Canada as t3 ON PostalCode = zip WHERE RequestDateTime > CONVERT(DATETIME, '2007-09-1 00:00:00', 102) AND interfacename LIKE '%download%' AND
result=0 AND country='CA' --AND t3.PostalCode Like 'z1x%' ORDER BY company_name I was trying to do it by using a Where clause AND t3.PostalCode Like 'z1x%' that I will later turn into an Input Parameter after I get it working. Is there anyway to trim the PostalCode to the first three characters during the join process? Something like Sales.dbo.RF_Postal_Code_Salesman_Canada as t3 ON LEFT(PostalCode, 3) = zip Not sure I got the LEFT function syntax correct even. Help appreciated.
I'm joining one table on to another table using one of 2 possibile fields (so table 1 key one can either match table 2 key 1 or key 2)... When the first key is null for a record, the script is to attempt to join using the second key instead. It is possible to have both values present, in which case the first one should be used.
I've taken a few runs at this so far:
... from table1 t1 left join table2 t2 on (t1.key1 = t2.key1 or t1.key1 = t2.key2)
If either t2.key1 or t2.key2 are populated, this works. Unfortunately, it's bringing back multiple records if both key1 and key2 are populated. Question # 1... Is there a different relational operator I can be using instead of OR that would logically look like 'if thie first key didn't find anything try the second instead'?
As an alternative, I've put the NVL to use...
NVL(t2.key1, t2.key2) = t1.key1
That seems to work, but it's pretty heavy on the server. Any suggestions on how else to handle this scenario would be greatly appreciated
view 1 I have a view that is drawing from two tables. Each table contains fields representing cube coordinates. The view is filtering the results based on some simple logic (where the defference between two values in the tables are greater than x) this part works fine.
view 2 notes field I want to include a note field in my view. This field will contain the contents of a note field from another view. This second view also contains coordinates that I can use to map the notes to the appropriate rows in view 1. However, if I join the views in my FROM clause, I will end up filtering my resultset down to rows that correspond to view 2's contents.
I want to have the full contents of view 1, displayed with a note field containing the note field content from view 2 only in the rows that have corresponding notes. (some rows will have notes, some will not)
so... my question: is there any way that I can include this field without joining the views in my FROM clause (meking my resultset exclusive)..... possibly somehow in fields list of the select statement?
like so often my Forums database design (in its simplest form) is:Forums -ForumID -Title -CategoryForumsMsgs -fmID -DateIn -AuthorID -MessageI need to create a sql query which returns all forum titles along with some data for 1) the first message entry (date created and author) and 2) the last one. So how can I do a JOIN query which joins with a ORDER BY clause so that the top/bottom entry only is joined from the messages table?
In simple terms, if possible, what is the difference between using the WHERE clause in a SELECT statement vs an INNER JOIN? According to Rob Viera's book the WHERE is "inclusive" in nature, meaning that all records that meet the WHERE condition are included in the result set. The text further stated that an INNER JOIN is "exclusive" in nature meaning that data not meeting the JOIN condition is excluded from the result set.
In layman's terms, what is the difference? Any examples? Thanks in advance.
I am trying to get all of the Fund_cdes to show up even if there was no transaction on the brkg fact table. The problem I coming up with is I am also retricting what I show in the brkg fact table so I am not getting all of the row from the fund table. How do I write a left join that shows all of the fund cdes
SELECT SEP_ACCOUNT.sep_acct_cde as Account, FUND.fund_cde as FUND, BRKG_FACT.accum_unit_cnt as Units_Purchased, BRKG_FACT.transaction_amt as Amount_Purchased FROM BRKG_FACT SEP_ACCOUNT FUND where BRKG_FACT.sep_acct_id_num = SEP_ACCOUNT.sep_acct_id_num brkg_fact.FUND_ID_NUM = FUND_DIM.FUND_ID_NUM brkg_fact.SEP_ACCT_ID_NUM = 5 and brkg_fact.product_cde <> 'MM' and brkg_fact.transaction_amt <= 0 and brkg_fact.source_sys_id_num <> 3 and brkg_fact.source_sys_id_num <> 5 and BRKG_FACT.trans_process_dte >= '1/1/2008' and BRKG_FACT.trans_process_dte <= '1/2/2008' order by fund_cde
current output
ACCOUNT FUND UNITS_PURCHASED AMOUNT_PURCHASED U BLCD -0.01137 -1.48000 U BOND -0.01283 -1.67000 U CGDE -0.06743 -0.95000 U EQIN -0.13277 -2.39000 U GRST -0.11799 -4.07000 U IX4S -0.53996 -12.55000 U LCCS -0.18216 -5.31000
wanted output ACCOUNT FUND UNITS_PURCHASED AMOUNT_PURCHASED U BLCD -0.01137 -1.48000 U BOND -0.01283 -1.67000 U BWDS NULL NULL U CGDE -0.06743 -0.95000 U EQIN -0.13277 -2.39000 U GAFR NULL NULL U GRST -0.11799 -4.07000 U IX4S -0.53996 -12.55000 U LIGE NULL NULL U LCCS -0.18216 -5.31000
I am reporting on a system with 32 devices, each of these devices can have certain events that happen to it that are logged and timestamped. I need a to show the count of each events that have happened to it within a certain time period. This code snippet below works fine BUT if there are no events that happen to a certain device in the time period, then that device is 'missing' from the table. What I need is basically a row for every device, regardless of if it has had any events happen to it (I will just show '0' for the event count) Any thoughts? I'm a complete newbie at this by the way.
Thanks
Code Snippet
SELECT DeviceStatusWords.DeviceName, COUNT(DeviceEventDurationLog.StatusBit) AS BitCount, DeviceEventDurationLog.StatusBit AS Bit FROM DeviceEventDurationLog RIGHT OUTER JOIN DeviceStatusWords ON DeviceEventDurationLog.DeviceID = DeviceStatusWords.DeviceID WHERE (DeviceEventDurationLog.TimeIn > @StartDate) AND (DeviceEventDurationLog.TimeIn < @EndDate) GROUP BY DeviceStatusWords.DeviceName, DeviceEventDurationLog.StatusBit ORDER BY DeviceStatusWords.DeviceName
Just curious. The exec plan is the same for both qry's, and they both show the same estimated row counts @ the point of question in the exec plan. The exec times are roughly the same, any variances I'm attributing to db load from other things going on, since any benefits of one over the other are not consistent from execution to execution. So is there any benefit to filtering in the join conditions vs. the where clause? My thinking was that by filtering earlier in the qry (when joining) as opposed to "waiting" to do it in the where clause, the rest of the qry after the join would inherently be dealing w/a smaller result set for the rest of it's execution, thus improving performance. After the exec plan checking I did, I guess I was wrong. Seems that Sql Server is intelligent about such filtering when analyzing the entire qry, and building its execution accordingly. The execution plan for both qry's showed the same where clause argument for the tables being joined.
Filtering in where clause....
Code:
select... FromtProject p with (noLock) jointProjectCall pc with (noLock) on P.ID = pc.project_id jointStore S with (noLock) on pc.store_id = s.id jointZip Z with (noLock) on Z.zip5 = s.zip5 jointManager M on M.ID = case ... end leftjoin ( selectprojectCall_RecNum as RecNum, sum(answer) as HoursUsed fromtCall C whereAnswer > 0 and question_id in (1, 2) group by projectCall_Recnum ) as C on pc.recnum = c.recnum wherepc.removed = 0 andp.cancelled = 0 andp.deleted = 0 ands.closed = 0 ands.deleted = 0 andyear(getDate()) between year(P.startDate) and year(P.expDate)
Filtering in joins...
Code:
select... FromtProject p with (noLock) jointProjectCall pc with (noLock) on P.ID = pc.project_id and pc.removed = 0 and p.cancelled = 0 and p.deleted = 0 and year(getDate()) between year(P.startDate) and year(P.expDate) jointStore S with (noLock) on pc.store_id = s.id jointZip Z with (noLock) on Z.zip5 = s.zip5 and s.closed = 0 and s.deleted = 0 jointManager M on M.ID = case ... end leftjoin ( selectprojectCall_RecNum as RecNum, sum(answer) as HoursUsed fromtCall C whereAnswer > 0 and question_id in (1, 2) group by projectCall_Recnum ) as C on pc.recnum = c.recnum