I've been running a long query which takes almost 39 seconds in Query Analyzer. After creating a Stored Procedure (with the same query) I expected to run it faster bcoz I heared that SP has a cache, and its a faster technique. But I didnt gain any performance improvments.
Can somebody clear my confusion, what I'm doing wrong.
hi friends the below query is actually what type of join whether inner join or normal query..?????
if not exists(select 'x' from cobi_invoice_hdr h(nolock), fin_quick_code_met q(nolock) , ci_adjustment_drdoc_vw z (nolock) where h.tran_ou = @ctxt_ouinstance and h.invoce_cat = @category_tmp and d.so_no between @sonumberfrom and @sonumberto
and isnull(h.tran_amount,0) between @totalinvoiceamountfrom and @totalinvoiceamountto and h.tran_date between convert(varchar(10),@invoicedatefrom,120)and convert(varchar(10),@fininvoicedateto,120) and h.tran_no between @invoicenumberfrom and @invoicenumberto and h.bill_to_cust between @billtocodefrom and @customerto and h.fb_id = isnull(@fb,h.fb_id) and h.tran_currency = isnull(@currency,h.tran_currency) and h.createdby = isnull(@useridentity,h.createdby)
and EXISTS (select '*' from cobi_cust_custinfo_vw c(nolock) where h.bill_to_cust = c.custcode andc.ouid = @ou_tmp )
and z.status = q.parameter_text
and q.parameter_type = 'STATUS' and q.parameter_category = 'STATUS' and q.component_id = 'COBI' and q.parameter_code = @status_tmp and h.tran_no = z.documentno and q.language_id = @ctxt_language and z.language_id = @ctxt_language) begin 'No matching invoices found.' select @m_errorid = 514 -- Porselvi.J - COBIDMS412AT_000255 return end End
I have a stored proc I want to convert it to either a Normal Query using A while loop or a set based operation/recursive cte as I want to run it for multiple CompanyNames. I get the error message as An INSERT EXEC statement cannot be nested when I execute if for Multiple Companies using another Cursor
If I convert it to a Function I get the below error message
Invalid use of a side-effecting operator 'EXECUTE STRING' within a function
converting this query to a normal query or let me know if there is any change which need to done to work with multiple companynames.
CREATE PROC [dbo].[USPT] @CompanyName varchar(50),@tablename varchar(50) AS BEGIN -- EXEC [USPT] 'xyz corp','Sales Header' DECLARE @str1 VARCHAR (MAX) set @str1 = ' DECLARE @No VARCHAR (MAX)
Guys can you tell me whether there is any difference between the following queries.......... Both of them are resulting same number of records. Not sure whether the output is same or not. Just wanted to know if result output wise if there is no difference than performance wise there might be some. Kinldy educate me on the same.
SELECT * FROM FRProposalOutline FPO INNER JOIN SC_Collection SCC ON FPO.Items= SCC.CollectionGID UNION SELECT * FROM FRProposalOutline FPO INNER JOIN SC_Collection SCC ON FPO.PageBreakPositions= SCC.CollectionGID
SELECT * FROM FRProposalOutline FPO INNER JOIN SC_Collection SCC ON FPO.Items= SCC.CollectionGID OR FPO.PageBreakPositions= SCC.CollectionGID
Hi, I have created a query (using SQL 2005) that will pull the people who have spent the most on tickets purchased:
Select P.Passenger_ID, Passenger_Name, Ticket_Price From Passenger P, Ticket_Purchase T Where P.Passenger_ID = T.Passenger_ID Group By P.Passenger_ID, Passenger_Name, Ticket_Price Having Ticket_Price >= All (Select Max(Ticket_Price) From Ticket_Purchase Group By Ticket_Price);
I now want to be able to only choose the Passenger_ID's from above who are not listed in another table called Frequent_Flier, which should leave me with only 2 records not 4.
I am wondering if I add the below to the first query to eliminate those passengers in the Frequent_Flier table: NOT IN (Select Passenger_ID From Frequent_Flier);
When I add it to the Where clause I get an error. Should I be sub-querying that differently or is there a better way to do this.
Hi, I have a BETWEEN query (at least I think that's what it will need), but with a difference.
Normally you would specific a field which was BETWEEN two set variables
ie. {fieldname} BETWEEN 1 AND 3
However I need mine the other way round.
I have a series of records which have a startdate and enddate held against them.
When a user submits a new record to the db, I need it to check that the starting and ending date range doesn't overlap any of the existing start-end date ranges that exist.
In order to do that I'm trying to build a query which takes in the incoming startdate variable and see if that is within any of the existing start-date-enddate dates ranges of the existing records, and then same for the incoming endate. I actually want the ones that are going to cause a problem to appear...
I;m sure there is a pretty easy way of coding this, but I'm struggling to get my head round it.
I have a table that will be loaded over night everyday and I need to write a query on running value difference ?
List of Columns (ID, Branch ,Group, Date, Value)
ID   Branch  Group  Date                 Value 1       A          C    2015-06-01           10 2       A          C      2015-06-02           15 3       A          C      2015-06-03           25 4        A          C      2015-06-04           20 5        B          D       2015-06-01           20 6        B          D       2015-06-02           25 7        B          D       2015-06-03           10 8        B          D       2015-06-04           20
I want the Output like below with a Running value difference in comparison to previous day.
ID   Branch  Group  Date         Value   Running Value 1       A          C    2015-06-01           10        10 2       A          C      2015-06-02           15         05 3       A          C      2015-06-03           25        10 4        A          C      2015-06-04           20        -5 5        B          D       2015-06-01           20        20 6        B          D       2015-06-02           25        05 7        B          D       2015-06-03           10        -15 8        B          D       2015-06-04           20        10
Basically I need to compare the previous day and show the difference. How can I do this in SQL 2008 r2?
We are trying to troubleshoot some website performance issues and found some queries taking 2 to 3 seconds when the request comes from the web, and captured by the Profiler.
The same queries, when run in the Query Analyzer take 0 seconds.
What could be the reasons for this difference, I mean why it takes 2 - 3 seconds shown by the Profiler, when it's 0 second in Analyzer?
Hi All,What are the pros and cons between using Enterprise Manager or QueryAnalyzer for my queries.Currently I use Enterprise Manager because I prefer the interface andonly use Query Analayzer when queries time out in Enterprise Manager,but I'm sure there must be more to it.Regards,Ciarán
I found an unusual problem between 2000 and 2005 I haven't been ableto decipher from any documentation.The query structure is as follows:select *fromtableA ajointableB b ON a.somekey = b.somekeywherea.type = 'A'and datediff(yyyy, b.someDateField, getdate()) betweena.lowboundary and a.highboundarySome basic facts about the elements and data. The low and high-boundary fields are varchar datatypes. In 2005 (regardless ofcompatibility type I run the database under), the query evaluates theBETWEEN and errors out due to the fact that it is evaluating theDATEDIFF as an integer and finds a non-integer entry in eitherlowboundary or highboundary. I understand and expect this behavior.Obviously, changing the result of the DATEDIFF function to varcharallows the operation to go forth.The odd thing is that there is no "a.type = 'A' " entry, thus thequery wouldn't return anything. In 2000, it seems as though theengine is evaluating the type = 'A' and short-circuiting and in 2005,it is trying to evaluate the entire query OR is there an implicitconversion occuring in 2000 and not in 2005?As I mentioned, the compatibility mode doesn't change how this reacts,but running this on a native 2000 server allows this to happen. Thisparticular code isn't the problem, it's what we might have to contendwith when we migrate this through. Sure, we're going to performregression testing, but I'm concerned about what we would miss.Thanks for any replies.
I have also posted this in microsoft.public.sqlserver.programming.
I have a query which, depending on where I run it from, will either take 10 milliseconds or 10 seconds.
The query works perfectly when run in SQL Server Management Studio... in my database of around 70,000 items it returns the results in around 10ms. It uses all my indexes and indexed views correctly.
However when I run the identical query from my ASP.NET application, it takes around 10 seconds... 1000 times longer. Looking at it in Sql Server Profiler I can't see any difference in the query, except from ASP.NET it needs 62531 reads and from SSMS it needs only 318 reads. If I copy the slow running ASP.NET query from the profiler into SSMS, then it runs quick again. The results returned are the same.
I have provided more details of the query below, but I guess my real question is: What is the best way to debug this? I'm not an expert with SQL Server, so any pointers on where I should start looking to find the difference in how the query is being executed would be a great help.
The query is of the form:
WITH RowPost AS ( SELECT ROW_NUMBER() OVER(ORDER BY DateCreated DESC) AS Row, ItemId, Title, .... FROM Items_View WITH(NOEXPAND) WHERE ItemX >= @minX AND ItemX <= @maxX AND ItemY >= @minY AND ItemY <= @maxY ) SELECT *, (SELECT Count(*) FROM RowPost) AS [Count] FROM RowPost WHERE Row >= @minRow AND Row < @maxRow
Where Items_View is an indexed view, and WITH(NOEXPAND) is being used to force it to use the indexed view (this is optimal). The line beginning "SELECT Count(*)" is to get the total number of results (without having to run the inner query a second time).
This is running against SQL Server Developer Edition.
Can any one tell me the difference between Select Query and SelectCommand in data adapters?
Using SelectCommand:
string selectSQL = "SELECT CustomerID, CompanyName FROM Customers WHERE Country = @Country AND City = @City"; SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");SqlDataAdapter custDA = new SqlDataAdapter(); SqlCommand selectCMD = new SqlCommand(selectSQL, nwindConn);custDA.SelectCommand = selectCMD; // Add parameters and set values.selectCMD.Parameters.Add("@Country", SqlDbType.NVarChar, 15).Value = "UK";selectCMD.Parameters.Add("@City", SqlDbType.NVarChar, 15).Value = "London"; DataSet custDS = new DataSet();custDA.Fill(custDS, "Customers"); Using Select Query:
SqlDataAdapter da = new SqlDataAdapter("select P_UID,P_EMIAL,P_NAME from p_users where p_email=@p_email and p_pwd=@p_pwd", con);
da.SelectCommand.Parameters.Add("@p_pwd", SqlDbType.VarChar, 50).Value = pwdtex.Text; Can you plz tell vat is the need for giving custDA.SelectCommand and adding parameters to that command instead of directly giving Select Query in Data Adapter? Similarly Update Command: custDA.UpdateCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID") custDA.UpdateCommand.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName")Dim myParm As SqlParameter = custDA.UpdateCommand.Parameters.Add("@OldCustomerID", _ SqlDbType.NChar, 5, "CustomerID")myParm.SourceVersion = DataRowVersion.Original[C#]custDA.UpdateCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID"); custDA.UpdateCommand.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName"); SqlParameter myParm = custDA.UpdateCommand.Parameters.Add("@OldCustomerID", SqlDbType.NChar, 5, "CustomerID");myParm.SourceVersion = DataRowVersion.Original; instead of above process, y cant v do above method in below procedure?
I have seen in this forum that many people has posted like my query time taken problem. But I couldn't get clear solution for this.
Here is the my issue:- I have written couple of batch query to bring data from another sql server. I have used proper index and index hints for these query. I have used SET NOCOUNT ON in stored procedure.
I am having the time difference for one of the blow qeury in various running process that executed in QA as single query , stored procedure for whole batch query and schedule this stored procedure in job
sotored Proc = 31 second > job =28 second > seperate query = 12 second.
one of 15 batch query
declare @last smalldatetime set @last ='11/08/2002'
UPDATE ENTERPRISE_STATE SET RESP_BUYER_FST_NAME = i.first_name, RESP_BUYER_LST_NAME = i.last_name FROM oesd.dbo.individual i WITH (NOLOCK index(XPKindividual)) INNER JOIN Leap.dbo.fnIndBuyer(@last) fn ON fn.individual_num=i.individual_num WHERE ENTERPRISE_NUM = fn.enterprise_num
Anbody can able to give proper reason why I am getting this time difference.
Executing the stored procedure took 45 seconds. But copying the code to a query window and setting up the variables (instead of parameters), it took 7 seconds.
In the query window, most of the processing cost (86%) is right up front in a "Distinct Sort." But in exec stored procedure, the cost for this step is 11% and the significant costs are in later "Table Scans."
I don't know why SQL Server would choose different execution plans when the code is identical in each.
I'm having an issue with a query I'm running on Sql Server 2005. It's a semi-complex query involving an in-line table function and several left outer joins which are joined on to the results of the function call. Two of the left outer joins are then qualified in a where clause of the form where table.Col is not null; the idea is that the final result set contains data that has no match in those two tables.
The problem revolves around a where clause in the function and the last left outer join (ie, one of the ones qualified with where not null). When I alter the where clause of the function to further restrict the result set the function returns, the query times shoots up from 1 second to roughly 2-3 minutes. Note that the time the function takes to complete is not affected. The difference in time is purely down to what the query does with the results the function provides. Also note that the change to the where clause provides a subset of the original data; it does not add any more data (it actually restricts the original resultset by roughly 1000 rows).
I can bring the query speed back down again by removing the last left outer join - this join takes one of the columns from the function, and joins it to a small table - 924 rows. So it appears that this particular join is the cause of the issue, but only when using the resultset generated from the modified function query.
Now, as the thread title alludes, Sql Server 2000 and 2005 handle this differently, or appear to. When I execute this same query on a Sql 2000 machine, there's no apparent time differences, and the data that is returned is as expected. Does anyone have any suggestions as to what might be causing this and how I can fix it? I could simply return the larger resultset and use managed code to filter out the rows I don't want; however, I would like to get to the bottom of this, especially if it's going to effect future queries.
I want to achieve something like below. It should subtract the '13' row to '6' row and provide another column with the result. the '6' and '13' category code share the same Key.
I have @Year and @Month as parameters , both integers , example @Year = '2013' , @Month = '11'
SELECT T.[Year], T.[Month]
-- select the sum for each year/month combination using a correlated subquery (each result from the main query causes another data retrieval operation to be run) , (SELECT SUM(Stores) FROM #ABC WHERE [Year] = T.[Year] AND [Month] = T.[Month]) AS [Sum_Stores], (SELECT SUM(SalesStores)
[code]....
What I want to do is to add more columns to the query which show the difference from the last month. as shown below. Example : The Diff beside the Sum_Stores shows the difference in the Sum_Stores from last month to this month.
How to write a Query for multiple legal names that have the same CARE Number (same address) with difference of one Legal Name having a period in the name versus the other legal name that doesn't.
For example: Looking for cases of two of the same legal name one set off by period
All Season Equipment Ltd. All Season Equipment Ltd
West End Housing, Inc. West End Housing, Inc
Wellings, Norman L. Wellings, Norman L
North Texas Boats, LLC North Texas Boats, L.L.C.
Oktibbeha County Cooperative (A.A.L.) Oktibbeha County Cooperative (AAL)
S & R Turf & Irrigation Equipment, L.L.C S & R Turf & Irrigation Equipment, L.L.C.
Burke Equipment Company; Burke Equipment-Seaford, Inc.; Newark Kubota, Inc. Burke Equipment Company Burke Equipment-Seaford, Inc.
Pleasant Valley Outdoor Power, L.L.C. Pleasant Valley Outdoor Power, LLC
J & D Lawn and Tractor Sales, Inc. J&D Lawn & Tractor Sales, Inc"
Hi. Sorry if I am asking a stupid question since I am an absolutely beginnerin SQL Server. Here is the question . . .About 13 hours ago, I got my SQL Server 2000 to index a table which has 104million records. At first the CPU usage was high. But after an hour or two,the process has seemed dead and the Enterprise Manager has had no response.The CPU usuage dropped to zero and has been jumping between 0 to 5%. Theharddisk indicator has been blinking at a rate of roughly three times pertwo seconds.Is this normal? Has anyone got any idea how long the process would take? Ihave assigned 1.8GB of RAM to the SQL service and is currently taking upabout 1GB.
Public Sub OpenConnexionSQL() ConnexionSQL = New SqlConnection(ConfigurationSettings.AppSettings("DataSourceSql").ToString) ConnexionSQL.Open() End Sub
Hi guys, I've been thinking about this problem now for some time but somehow I don't know if my "solution" for it is right. I'd like to read your opinion.
There is a Capital table with Capital_Nr, Capital_Name, Capital_Population, Country_Nr and Country_Name as attributes.
I know the table is chaotic so I brought it to 3NF :
Capital table : Capital_Nr, Capital_Name, Capital_Population, Country_Nr(foreign key)
Country table : Country_Nr and Country_Name
Ok so I guess the table should be now in 3NF, but what intrigues me is in what NF the table originally was. I tried then to use Codd's definition of 2NF : "a 1NF table is in 2NF if and only if none of its non-prime attributes are functionally dependent on a part (proper subset) of a candidate key". In my opinion the original candidate keys could only be {Capital_Nr},{Country_Nr} and {Country_Name}, each one of them single, i.e. separate from each other. So, as there is no composite candidate key, I can affirm that the original table was in 2NF. Am I right ?
I am wondering what normal disk I/O should be. i know it verys depending on use but im looking for an average.
here is an idea of what we have
there is about 10 centers doing replication to our primary server. we have about 80 users connecting directoy to our primary server using MS Dynamics through CITRIX. we have a few other apps use the database as well however i am fairly certin its Dynamics generating our disk IO Hardware wise we have a powerful blade connected to a raid 5 SAN with 15000 rpm disks. normaly the disk IO stays fairly low but every so often it goes crazy and im thinking it shouldn't
Below is a sample of our disk IO from perfmon over 2 minutes or so. as you can see everything looks ok untill 04/15/2008 10:12:49.470 when the Disk I/O % goes above 100%
Hey All, I'm trying to decide what's the 'best' to use. I've been designing and creating database for a while and have pretty much always used a surrogate key and not a normal one. I've finally had some free time to start studying more so in my spare time and read up and come accross a lot of guides, articles and stories that tout that normal keys should be used whenever possible as they're a better identifier and that surrogate keys should only be used when there is not a readily available normal key. Now perhaps I'd be open to accepting that but absolutely every database I come across tends to only use surrogate keys. For example I'm doing an authentication system from scratch and am looking at the User table. Now of course the user name has to be unique, should that be the primary key or should I have a seperate column with a guid or an incrementing int or the like as the primary key? I can certainly see that username could be used. I can also see how it may be easier when looking through the data tables to identify who/what a table is refering to with a surrogate key. However it still seems sort of sloppy, for lack of a better word, to me. Where now I could have somebody's username (or any other piece of data used for this purpose) spread accross a lot of other tables. And while writting this I just thought of the scenario that perhaps somebody needs their username changed, with this method now the ids need to be changed on all the related rows of all the other tables whereas with a surrogate key it wouldn't matter. Anyways I'm mostly looking for opinions on which way to go (not just with the user sample, but more in general).Thanks.
We have a payroll database that needs to be backed up just before completing the payroll for that period. I need to create a batch file that a normal user can run that will tell the database to back up and then tell the user when it is done so they can continue working. Is there an easy way to do this without giving the users special permissions? I don't want to give them backup op status. Any help would be appreciated.
I will be taking over a database that has almost no pk's or relations(this is not my choice, but a vendors) Management is looking at stored procs to improve performance, but I am wondering if the db is in this state will there really be a gain. I am pushing for normalization first, but if anybody has any ideas or opinions I would appreciate
Is performance of web application (ASP.NET + SQL Server 2005 Wrg edition + Win Server 2003 Web edition) running on server with one core duo/4 CPU generally comparable to the performance of the same application running on the same server with 2/4 physical CPU’s?
My sql database is in suspect mode, please help me with step by step how can i change the suspect status to normal status, please dont provid eme the links of other site and help me in your own language
iam getting following error:
TITLE: Microsoft SQL Server Management Studio------------------------------ An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo) ------------------------------ADDITIONAL INFORMATION: Database 'msdb' cannot be opened. It has been marked SUSPECT by recovery. See the SQL Server errorlog for more information. (Microsoft SQL Server, Error: 926) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=09.00.1399&EvtSrc=MSSQLServer&EvtID=926&LinkId=20476 ------------------------------BUTTONS: OK------------------------------Thanks in advance