Optimizing Queries / Stored Procedure For Retreiving Millions Of Rows

Apr 22, 2006

I am having one querry regarding the same line.
In my stored procedure i am fetching the data from one table containing upto 5 to 6 million rows I made use of index in my database but then also I cant optimise my execution time of that sp.
Please help me out of this problem.

View 1 Replies


ADVERTISEMENT

Optimizing Stored Procedure

Feb 4, 2008

Hi all,
I have have this stored procedure which gets records from the SQL Server database which are then displayed on a web page. In the second part of the stored procedure, it has the exact same SELECT statement as in first part but it just returns the total duration. I have noticed that when the number of records is very large, the CPU time goes up to 100% for a second (while its fetching data) and then goes back to normal.
Please guide me to what optimizations can be done to this procedure. CREATE Procedure GetCDR_LikeTollFree
(
@theDuration int = null, --to find duration more than theDuration
@totalDuration bigint = null, --to find the total duration for the result set
@callerName varchar(255) = null,
@callingPartyNumber varchar(255) = null,
@originalCalledPartyNumber varchar(255) = null,
@finalCalledPartyNumber varchar(255) = null,
@dateTimeConnect datetime = null,
@dateTimeDisconnect datetime = null,
@clientMatterCode varchar(255) = null
)

AS
BEGIN
SELECT callingPartyNumber, AlertingName, originalCalledPartyNumber, finalCalledPartyNumber,
dateTimeConnect,
dateTimeDisconnect,
CONVERT(char(8), DATEADD(second, duration, '0:00:00'), 108) AS duration,
clientMatterCode


FROM CDR1.dbo.CallDetailRecord t1
LEFT JOIN CDR2.dbo.NumPlan t2 ON t1.callingPartyNumber=t2.DNorPattern

WHERE
(t1.callingPartyNumber LIKE ISNULL(@callingPartyNumber, t1.callingPartyNumber) + '%') AND
(t1.originalCalledPartyNumber LIKE ISNULL(@originalCalledPartyNumber, t1.originalCalledPartyNumber) + '%') AND
(t1.finalCalledPartyNumber LIKE ISNULL(@finalCalledPartyNumber, t1.finalCalledPartyNumber) + '%') AND
(t1.clientMatterCode LIKE ISNULL(@clientMatterCode, t1.clientMatterCode) + '%') AND
(@callerName is NULL OR t2.AlertingName LIKE '%' + @callerName + '%') AND
(t1.duration >= @theDuration) AND
((t1.datetimeConnect) >= ISNULL(convert(bigint,
datediff(ss, '01-01-1970 00:00:00', @dateTimeConnect)), t1.datetimeConnect)) AND
((t1.dateTimeDisconnect) <= ISNULL(convert(bigint,
datediff(ss, '01-01-1970 00:00:00', @dateTimeDisconnect)), t1.dateTimeDisconnect))


SET @totalDuration = (SELECT SUM(duration)

FROM CDR1.dbo.CallDetailRecord t1
LEFT JOIN CDR2.dbo.NumPlan t2 ON t1.callingPartyNumber=t2.DNorPattern


WHERE

(callingPartyNumber LIKE ISNULL(@callingPartyNumber, callingPartyNumber) + '%') AND
(originalCalledPartyNumber LIKE ISNULL(@originalCalledPartyNumber, originalCalledPartyNumber) + '%') AND
(finalCalledPartyNumber LIKE ISNULL(@finalCalledPartyNumber, finalCalledPartyNumber) + '%') AND
(clientMatterCode LIKE ISNULL(@clientMatterCode, clientMatterCode) + '%') AND
(@callerName is NULL OR t2.AlertingName LIKE '%' + @callerName + '%') AND
(duration >= @theDuration) AND
((datetimeConnect) >= ISNULL(convert(bigint,
datediff(ss, '01-01-1970 00:00:00', @dateTimeConnect)), datetimeConnect)) AND
((dateTimeDisconnect) <= ISNULL(convert(bigint,
datediff(ss, '01-01-1970 00:00:00', @dateTimeDisconnect)), dateTimeDisconnect))

)

RETURN @totalDuration

END
GO
 

View 13 Replies View Related

Optimizing Stored Procedure With Datetime Parameter

Nov 23, 2005

Hi,When I pass a date time parameter the stored procedure takes about 45seconds, when I hard code the parameter it returns in 1 second. How canI rewrite my stored procedure?@createddatelower datetimeWHERE dbo.tblCaseHistory.eventdate > dateadd(d,-7,@createddatelower )AND dbo.tblCaseHistory.eventdate < dateadd(d,-6,@createddatelower ) (45seconds)vs.WHERE dbo.tblCaseHistory.eventdate > dateadd(d,-7,'11/15/05') ANDdbo.tblCaseHistory.eventdate < dateadd(d,-6,'11/15/05') (1 second)thanks for your help,Paul

View 5 Replies View Related

SQL Server 2012 :: Optimizing Stored Procedure To Go Parallel

Jan 22, 2015

I have a stored procedure that calls several views that rely on each other. In the past these views used to go parallel and use up all 100% of the CPU (12 cores), and now when the same stored procedure runs it only uses 8% of the CPU (1 core). This extends the time spent on the query from roughly 10-15 sec to 2-3min. I'm not quite sure why this is happening.

Are there some obvious things to look at when optimizing views to utilize all cores/threads? Also, it doesn't matter if I set Cost Threshold for Parallelism to 1 or 50 or 5, it is always the same, and I have Max Degree of Parallelism set to 0 as well, which should mean to use all cores when available.

View 9 Replies View Related

Need Help Optimizing Slow SQL Queries (?)

Aug 6, 2007

Hi, I have absolutely no knowledge of PHP or SQL .... I moderate a PHPBB forum at www.savingshelterpets.com
Our web host (SiteGround) has taken our site down temporarily because we are overloading the server. I have no idea how to fix the problem, so hopefully someone here can help me out! Smiley

PHP version 4.4.4
MySQL version 5.0.27-standard-log

Here's the info sent to me by SiteGround (I don't understand a word of it!):

quote:Upon further investigation, it turned out that the following queries in your account are slow and heavily consume server resources:

# User@Host: savingsh_phpb1[savingsh_phpb1] @ localhost []
# Query_time: 4 Lock_time: 0 Rows_sent: 1 Rows_examined: 1284
use savingsh_phpbb2;
SELECT user_id, username, user_password, user_active, user_level, user_login_tries, user_last_login_try
FROM phpbb_users
--
delete from rs_stat_ip where platnost_do<'2007-08-03 16:49:43';
# User@Host: savingsh_phpb1[savingsh_phpb1] @ localhost []
# Query_time: 5 Lock_time: 3 Rows_sent: 1 Rows_examined: 0
use savingsh_phpbb2;
SELECT * FROM phpbb_optimize_db;
# User@Host: binaryte_lhlp1[binaryte_lhlp1] @ localhost []
--
# Time: 070803 16:50:27
# User@Host: savingsh_phpb1[savingsh_phpb1] @ localhost []
# Query_time: 4 Lock_time: 2 Rows_sent: 1 Rows_examined: 0
use savingsh_phpbb2;
SELECT t.topic_id, t.topic_title, t.topic_status, t.topic_replies, t.topic_time, t.topic_type, t.topic_vote, t.topic_last_post_id, f.forum_name, f.forum_status, f.forum_id, f.auth_view, f.auth_read, f.auth_post, f.auth_reply, f.auth_edit, f.auth_delete, f.auth_sticky, f.auth_announce, f.auth_pollcreate, f.auth_vote, f.auth_attachments
FROM phpbb_topics t, phpbb_forums f

In order to have the limitations removed, please optimize your script.

View 3 Replies View Related

Optimizing Queries Generated At Runtime

Sep 5, 2007

Hi

We are using SQL SERVER 2005, enterprise/standard edition for an application that generates queries at runtime and normally having many joins in it. But these queries are taking lot of time when they are executed. After setting the database parameter PARAMETERIZATION to FORCED, performance of the queries have improved a lot but still we want to improve them further. Is there any other parameter that we can set for improving the performance of the queries. We have created the indexes on the basic columns that will be used while querying but it may happen that some other columns may also be used for searching in which case queries become quiet slow. Is there anything like skip-scan indexes(of oracle) in sql server 2005.

Regards
Salil

View 4 Replies View Related

Inserting Millions Of Rows

May 26, 2004

hi everybody,

i have an application that generate a lot rows from 1 mellion to 2 mellions rows
i wana insert this record in MS SQL server in a fast way

i am currentlly loop through this records while it is loaded in dataset
building a command text that generate insert query for each row
and run it against SQL server

but it takes a lot of time to be finished
is there r a way to bulk insert this data?

thanks 4 ur help.
Bolos

View 7 Replies View Related

10 Millions Rows - 45 Minutes??

Feb 21, 2008



Hi everyone - I have an ETL package which loads about 10 million rows from SQL 2005 staging tables to new, empty tables (no indexes or constraints) in another SQL 2005 DB to be SWITCHED into the main partioned data tables.

Both databases reside on the same SQL Server instance - it is a dev server so the disk aren't super fast/SAN speeds but it has plenty of RAM/CPU & SCSI disks.

The insert takes about 45 minutes - can I get this working any faster?? or is this typical for 10 million rows?? I've messed about withe the data flow a few times but I can't seem to get any significant improvements.

Any tips anyone??

I perform several lookups on dimensions - these are not cached.

I do query the source table concurrently with different WHERE clauses & run two pipelines processing the data into 2 destination tables.

Would it be better to query the base table once & use a conditional split instead of the two separate queries??

I also mulicast from each pipeline & use a UNION ALL to log some of the rows from each pipeline to anther destination table.

Hope this makes sense?? Any ideas or tips on how I can speed up this kinda transform would be appeciated..

I'm using oleDB connections.

Hope ths makes some kinda sense!! Thanks for any advice!!

Sinister Pengiun

View 5 Replies View Related

SQL Server 2012 :: Update Statement Will Not Update Data Beyond 7 Million Plus Rows Out Of 38 Millions Rows

Dec 12, 2014

I run the following statement and it will not update beyond 7 million plus rows and I have about 38 million to complete. I keep checking updated row counts and after 1/2 day it's still the same so I know something is wrong because it was rolling through no problem when I initiated it. I need to complete ASAP so it's adding to my frustration. The 'Acct_Num_CH' field is an encrypted field (fyi).

SET rowcount 10000
UPDATE [dbo].[CC_Info_T]
SET [Acct_Num_CH] = 'ayIWt6C8sgimC6t61EJ9d8BB3+bfIZ8v'
WHERE [Acct_Num_CH] IS NOT NULL
WHILE @@ROWCOUNT > 0
BEGIN
SET rowcount 10000
UPDATE [dbo].[CC_Info_T]
SET [Acct_Num_CH] = 'ayIWt6C8sgimC6t61EJ9d8BB3+bfIZ8v'
WHERE [Acct_Num_CH] IS NOT NULL
END
SET rowcount 0

View 5 Replies View Related

Retrieving And Sorting Millions Of Rows

Oct 11, 2007

Hello,Currently we are in the process of implementing a sql server database where couple tables will have millions of rows ( about 98 millions and will grow) and a web site that will retrieve and sort the data ( read only). How asp.net gridview and sqldatareader act situation like that? Will it be a very slow response? Is there any alternative? Is there any example on the net?
Assuming tables are well tuned and well indexed.
Thank you in advance.

View 4 Replies View Related

Inserting Millions Of Rows Into A Table

Aug 10, 2006

Hi,

I have a DataTable in memory and I want to write a C# code to dump the data into a SQL database. Is there a faster way of dumping millions of rows into a SQL table besides running INSERT INTO row by row?

Thank you,

Jina

View 3 Replies View Related

SQL Server Installing With Millions Or Rows In Tables

Oct 11, 2007


Hello,
Currently we are in the process of implementing a sql server database where couple tables will have millions of rows (about 98 millions and will grow) and an asp.net site that will retrieve and sort the data

What will be the best practice installing the database in situation like this one?
Do we need a cluster server? Indexing needs to be done in a special way?
Thanks in advance.

View 5 Replies View Related

Truncate A Huge Table Having 21 Millions Of Rows

Nov 19, 2015

SQL Server: 2008 R2

Question A :  I need to truncate a table, it has 21 millions of rows and it has a size of 14 GB.             

                                1-  How do I find out if this table is not being referenced by a FOREIGN KEY?
                                2-  Does it Participates in a indexed view?
                                3- Is being published by using transactional replication or merge replication?

Question B:  How do I safely truncate that table? 

View 8 Replies View Related

SQL Server 2008 :: Best Way To Optimize View That Contains Millions Of Rows?

Aug 26, 2015

I have one view which is based on couple of tables. Here is the definition of view. Which are the options i can use to optimize the view for better performance. This is one of the view which causing issue on database.

CREATE VIEW [dbo].[V_Reqs]
WITH SCHEMABINDING
AS
SELECT purchase.Req.RequisitionID, purchase.Req.StatusCode AS Expr2, purchase.Req.CollectionDateTime,
purchase.Req.ReportDateTime, purchase.Req.ReceivedDateTime, purchase.Req.PatientName, purchase.Req.AddressOne,
purchase.Req.AddressTwo, purchase.Req.City, purchase.Req.PostalCode, purchase.Req.PhoneNumber,

[code]....

View 3 Replies View Related

Rows Skipped Out In Stored Procedure While Return All Rows If Query Executed Seprate

Nov 8, 2007

Hi All,

I am using sql server 2005. I stuck out in a strange problem.
I am using view in my stored procedure, when I run the stored procedure some of the rows get skipped out means if select query have to return 10 rows then it is returning 5 rows or any other but not all, also the records displyaing is randomly coming, some time it is displaying reords 12345 next time 5678, other time 2468.

But if I run seperately the querys written in SP then it returns all the rows. Please give me solution why it is happening like this.

There are indexes in the tables.

Once I shrink the database and rebuild the indexes, from then this problem is happening. I have rebuild the indexes several time, also updated the statistics but nothing improving.


But nothing is improving

View 7 Replies View Related

2 Different Queries In One Stored Procedure

Dec 3, 2003

Hi ya'll! First off, please let me know if I'm totally doing the wrong thing here ...

I have set up two different simple queries in one stored procedure that I'd like to reference from one fetch from my ASP.Net/VB.Net web template. Can I do this? I think I can, 'cause most of the data is showing up.

Code follows:
[stored procedure]

CREATE PROCEDURE dbo.sp_admin_vStatistics
AS
BEGIN

SELECT COUNT(metric_ID) AS device_totalRequests, MAX(request_due_date) AS device_maxRequest_due_date, MIN(request_due_date) AS device_minRequest_due_date,
MAX(metric_log_dtTime) AS device_maxLog_dtTime,
FROM dbo.metrics

SELECT COUNT(user_ID) AS user_total, MAX(user_lastlogin_dtTime) AS user_LastLogin
FROM dbo.users

END
GO


[snippet of .Net page where I'm actually trying to display the output]

'Loop over our query results & print it
Do While (dr.Read())
lblUser_Total.Text = CType(dr("user_total"), Integer)
lblUser_LastLogin.Text = CType(dr("user_LastLogin"), Date)
lblDevice_TotalRequests.Text = CType(dr("device_totalRequests"), Integer)
lblDevice_minRequest_due_date.Text = CType(dr("device_minRequest_due_date"), Date)
lblDevice_maxRequest_due_date.Text = CType(dr("device_maxRequest_due_date"), Date)
lblDevice_minLog_dtTime.Text = CType(dr("device_minLog_dtTime"), Date)

Loop


My output shows nothing for user_total and user_lastlogin, but the other "device" information gets properly displayed. Running SQL Query Analyzer shows it all. I just think I'm referencing it incorrectly.

Any suggestions? Thanks in advance for any ideas.

Brent

View 3 Replies View Related

2 Queries, One Stored Procedure

Jan 23, 2008

I am trying to create a stored procedure to be called from an ASP.Net page.

There are two sets of stats that I want to be able to pull off for a given ID - firstly a list of all the names given and the number of times that name has been given and secondly a list of all the reasons given and the number of times for each reason.

With the queries there is clearly different Group By required to get the necessary stats off.

I dont want to have to make two round trips to the server to get the two different results but cannot see how to otherwise to get the results out and into ASP.Net to consume?

Any ideas anyone?

View 2 Replies View Related

SQL Server 2012 :: Strategy To Delete / Move Millions Of Rows In A Database?

Apr 16, 2015

I am using SQL Server 2012 SE.I am trying to delete rows from a couple of tables (GetPersonValue has 250 million rows and I am trying to delete 50Million rows and GetPerson has 35 Million rows and I am trying to delete 20 million rows). These tables are in TX replication.The plan is to delete data older than 400 days old.

I tried to move data to new tables from the last 400 days and it took me like 11 hours. If I delete data in chunks of 500000 then its taking a long time to rebuild indexes(delete plus rebuild indexes 13 hours). Since I am using standard edition partition wont work.

find ddl below:

GO
CREATE TABLE [dbo].[GetPerson](
[GetPersonId] [uniqueidentifier] NOT NULL,
[LinedActivityPersonId] [uniqueidentifier] NOT NULL,
[CTName] [nvarchar](100) NULL,
[SNum] [nvarchar](50) NULL,
[PHPrimary] [nvarchar](50) NULL,

[code]....

View 1 Replies View Related

SQL 2012 :: Data Size Of Table Is Not Reduced Even After Deleting Millions Of Rows

Sep 21, 2015

I have deleted nearly 30 million rows from a table. But however when I used the sp_spaceused command to calculate the data occupied by the table I don't see any difference in the data size of the table. In fact the data has increased to few MBs after the deletion, but not much.

View 8 Replies View Related

Creating A Stored Procedure From 3 Queries

Jul 20, 2005

Hi all,Sorry for HTML, there is a lot of code & comments I tried to create a stored procedure from 3 queries .. to reduce # of times DB gets access from 1 asp page. The result procedure only works 1/2 way (does return the rest of the SELECT statement) :( Please help me figure out what stops it mid way? I need it to return all the results from the SELECT statements AND the number of rows (ScriptsNo) from the count(*): Here is my stored procedure:CREATE PROCEDURE csp_AuthorAccountInfo@CandidateID int,AS DECLARE @ScriptsNo int, @ManuscriptID int SELECT count(*) as ScriptsNo FROM Manuscripts WITH (NOLOCK) WHERE CandidateID = @CandidateID/* this is where it stops all the time :(Theoretically speaking, next SELECT will only return 1 row with Candidate's info*/SELECT c.*, l.LocationID, @ManuscriptID=m.ManuscriptID, l.State, cn.Country FROM Candidates c INNER JOINManuscripts m ONc.CandidateID = m.CandidateID INNER JOINLocations l ON c.LocationID = l.LocationID INNER JOINcn ON l.CountryCode = cn.CountryCodeWHERE c.CandidateID = @CandidateID/* next SELECT should normally return manu rows with Candidate's submitted manuscripts */SELECT m.ManuscriptID, m.IsReceived, msn.StageName, ms.DatePosted, ns.CommentsFROM Manuscripts m INNER JOINManuscriptStages ms ON m.ManuscriptID = ms.ManuscriptID INNER JOINManuscriptStageNames msn ON ms.StageNameID = msn.StageNameIDWHERE m.ManuscriptID = @ManuscriptIDORDER BY ms.DatePosted DESCGO

View 2 Replies View Related

Three Queries Of One Table As One Stored Procedure?

Nov 1, 2007



Hi,
I currently have three queries running seperately which I'd like to join up..

However I'm sure it can be done..

Here goes:

I have one table which lists payments made (it stores a PaymentID from another table, a payment amount and an invoiceID)

Therefore there can be several records with the same PaymentID referenceing different invoices (i.e a user paying off several invoices with one payment)

I have one query which lists all of the invoices paid against one payment.

SELECT PaymentID, InvoiceID, PaymentAmount WHERE PaymentID = xxx AND PayType <> 'Credit'

I then have a second query which is ran against each individual invoice which shows the other payments which have been made against this invoice already


SELECT PaymentID, InvoiceID, PaymentAmount WHERE PaymentID <> xxx AND PayType <> 'Credit' AND InvoiceID = XXX


and final I have one query which lists the credits
SELECT PaymentID, InvoiceID, PaymentAmount WHERE PayType = 'Credit' AND InvoiceID = XXX


All of the above lets me see an payment, which invoices have been paid against that payment.. and then for each invoice, any other payment which were made beforehand, and finally any credits against that invoice.


I run these from an ASP page in a loop which is pretty inefficient way of doing it.

I would much prefer to amalgamate the three queries above so I could see what I was paying now, what had already been paid and what was credited against each invoice from a PaymentID.. all in query.

Is that possible?

Thanks
mtm81


View 5 Replies View Related

SQL Stored Procedure Can't Insert , Parameterized Queries...

May 16, 2004

I have a SQL stored procedure like so:

CREATE PROCEDURE sp_PRO
@cat_num nvarchar (10) ,
@descr nvarchar (200) ,
@price DECIMAL(12,2) ,
@products_ID bigint
AS
insert into product_items (cat_num, descr, price, products_ID) values (@cat_num, @descr, @price, @products_ID)


when I try and insert something like sp_PRO '123154', 'it's good', '23.23', 1

I can't insert "'" and "," because that is specific to how each item is delimited inorder to insert into the stored procedure. But if I hard code this into a aspx page and don't create a stored procedure I can insert "'" and ",". I have a scenario where I have to use a stored procedure...confused.

View 3 Replies View Related

What's The Best Way To Create A Stored Procedure That Queries With Multiple Parameters?

Nov 21, 2007

 
If I were to create a stored procedure that searches a table using (optional) multiple parameters, what would be the best way to do the search.  I want to try and avoid using several "IF" statements (like IF @FirstName IS NOT NULL, etc).  How would I do it, or would I just be better off using several "IF" statements?  Thanks...
 CREATE PROCEDURE intranet_search_GetEmployeesBySearch
(
@FirstName NVarChar(100),
@LastName NVarChar(100),
@Phone NVarChar(50),
@Cell NVarChar(100),
@Pager NVarChar(100),
@Ext NVarChar(50),
@Email NVarChar(100),
@Department NVarChar(200),
@Position NVarChar(100),
@IsManager Bit
)
AS
BEGIN

SET NOCOUNT ON;




END
GO 

View 8 Replies View Related

SQL Server 2012 :: Multiple Queries In Same Stored Procedure

Sep 16, 2015

Our developers have gotten this idea lately that instead of having many small stored procedures that do one thing and have small parameter lists that SQL can optimize query plans for, its better to put like 8-10 different queries in the same stored procedure.

They tend to look like this:

create procedure UberProc (@QueryId varchar(50))
as

if @QueryId = 'First Horrible Idea'
begin
select stuff from something
end
if @queryid = 'Second really bad idea'
begin
select otherstuff from somethingelse
end

I see the following problems with this practice:

1) SQL can't cache the query plan appropriately
2) They are harder to debug
3) They use these same sorts of things for not just gets, but also updates, with lots of optional NULLable parameters that are not properly handled to avoid parameter sniffing.

View 9 Replies View Related

All Select Queries From Stored Procedure Not Appearing Under Dataset

Jan 29, 2008

I have 4 sets of select queries under 1 stored proc, now on the report calling the stored proc via dataset. when i run the dataset the only first set of the select query related fields appearing under the dataset.

But on the back end sql server, if i execute the same stored proc, i get 4 resultsets in one single executioln.

i am not seeing the remaingin 3 resultsets, on the reports dataset.

Is it possible on the reports or not.

In the asp.net project i was able to use that kind of stored procedures whcih has multiple select statements in 1 procedure., i use to refer 0,1,2,3 tables under a dataset.

Thank you all very much for the information.

View 1 Replies View Related

Creating A Stored Procedure With Parameters And Multiple Sql-server Queries

Jan 23, 2008

I need to create a stored procedure that will have about 10-15 queries and take 3 parameters.
 the variables will be: @lastmonth, @curryear and @id
@lastmonth should inherit Session variable intlastmonth
@curryear should inherit Session variable intCurrYear
@id should inherit Session id
 One example query is SELECT hours FROM table WHERE MONTH ='" + Session("intLastmonth") + "'  AND YEAR ='" + Session("intCurrYear") + "' AND [NUMBER] = '" + Session("id")
The rest of the queries will be similar and use all 3 variables as well.
How can I go about this and how will queries be seperated.
 

View 2 Replies View Related

Using Multiple Distinct Queries Inside Single Stored Procedure

Feb 21, 2008

Hello,

I was wondering if anyone can explain the positives and negatives of using a single stored procedure that contains one or more distinct queries. I know there are problems with dynamic SQL but I am not proficient enough to know whether this falls under that umbrella.

For clarification, what I am referring to is this: In a single stored procedure, I have a parameter called Query_ID that is used to identify which query in the sproc that I want to execute. Then from my ASP page, I simply pass the appropriate value for Query_ID. So:

IF @QUERY_ID = 1
BEGIN
SELECT [whatever]
FROM [tbl1]
WHERE [conditions]
GROUP BY [something]
ORDER BY [somethingelse]
END
ELSE
IF @QUERY_ID = 2
BEGIN
SELECT [whatever]
FROM [tbl2]
WHERE [conditions]
GROUP BY [something]
ORDER BY [somethingelse]
END
END

I hope that makes sense. Thanks in advance.

View 7 Replies View Related

Calling Three Different Variable Coming From Three Different Sql Queries Which Defined In Same Stored Procedure From DataAdapter

May 22, 2008

 
My task is to bind and show 3 different values coming from three different queries into three different columns of GridView. I had done this as mention in below. Program was successful. But I want to excute these three queries in same Stored Procedure. I can do that and stored in seperated variables. I need help how to call these three different values in data adapters and store each value in three different columns of grid view.
 
Simply I want to below statement in stored procedures and call from program.  Can any one help me plz.
 
 
 
 
con = DataBaseConnection.GetConnection();
 
DataSet ds = new DataSet();
           
SqlDataAdapter da = new SqlDataAdapter("select isnull(sum(PA_DAmt),0) from PA_Deposits where PA_UID = @PA_UID", con);
da.SelectCommand.Parameters.Add("@PA_UID", SqlDbType.Int).Value = Convert.ToInt32(Session["PA_UID"]);
da.Fill(ds,"Dep");
           
SqlDataAdapter da1 = new SqlDataAdapter("select isnull(sum(PA_EAmt),0) from PA_Expenses where PA_UID = @PA_UID", con);
da1.SelectCommand.Parameters.Add("@PA_UID", SqlDbType.Int).Value = Convert.ToInt32(Session["PA_UID"]);
da1.Fill(ds,"Exp");
           
           
SqlDataAdapter da2 = new SqlDataAdapter("select isnull(sum(PA_IAmt),0) from PA_Income where PA_UID = @PA_UID", con);
da2.SelectCommand.Parameters.Add("@PA_UID", SqlDbType.Int).Value = Convert.ToInt32(Session["PA_UID"]);
da2.Fill(ds,"Inc");
 
string deposits = Convert.ToString(ds.Tables["Dep"].Rows[0].ItemArray[0]);
string expenses = Convert.ToString(ds.Tables["Exp"].Rows[0].ItemArray[0]);
string income = Convert.ToString(ds.Tables["Inc"].Rows[0].ItemArray[0]);
           
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.Rows[0].Cells[0].Text = "Total";
GridView1.Rows[0].Cells[1].Text = deposits
GridView1.Rows[0].Cells[2].Text = expenses;
GridView1.Rows[0].Cells[3].Text = income;
//The above program was success.
 
// This is another way I had tried. But failed. I am getting Index out of bound error. Can any solve this if possible to u.
SqlCommand cmd = new SqlCommand("select isnull(sum(PA_DAmt),0) from PA_Deposits where PA_UID = @PA_UID", con);
cmd.Parameters.Add("@PA_UID", SqlDbType.Int).Value = (int)Session["PA_UID"];
GridView1.Rows[0].Cells[1].Text = cmd.ExecuteScalar().ToString();
 
cmd.CommandText = "select isnull(sum(PA_EAmt),0) from PA_Expenses where PA_UID = @PA_UID";
GridView1.Rows[0].Cells[2].Text = cmd.ExecuteScalar().ToString();
 
cmd.CommandText = "select isnull(sum(PA_IAmt),0) from PA_Income where PA_UID = @PA_UID";
GridView1.Rows[0].Cells[3].Text = cmd.ExecuteScalar().ToString();
 
ASPX Code for Grid View
<h2>Account Summary</h2><br />
  
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" emptydatatext="There are no data records to display." Width="238px" >
            <Columns>
                <asp:TemplateField >
                   
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text="Total"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField   ><%--HeaderText="Deposits"--%>
                    <ItemTemplate>
                       
                    
                    </ItemTemplate>
                    <HeaderTemplate>
                        <a href="Deposits.aspx" >Deposits</a>
                    </HeaderTemplate>
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
              
                <asp:TemplateField >
                    
                     <HeaderTemplate>
                        <a href="Expenses.aspx">Expenses</a>
                    </HeaderTemplate>
                    <ItemStyle HorizontalAlign="Center" />
                    <ItemTemplate>
                  
                   
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField   >
                    <HeaderTemplate>
                        <a href="Income.aspx">Income</a>
                    </HeaderTemplate>
                  
                 
                    <ItemStyle HorizontalAlign="Center" />
                    <ItemTemplate>
                   <%-- <%# Eval("Course") %>--%>
                    
                    </ItemTemplate>
                </asp:TemplateField>
              
            </Columns>
        </asp:GridView>
 
Plz solve this.

View 4 Replies View Related

Optimizing Stored Procedures

Nov 21, 2006

hi all,
i'm working in a database, i'm not the creater of it, and was assigned to optimize the stored procedures running against this database.
can someone tell me what steps should i follow to check these SP's and to what should i look at and what can be done to optimise them.

thanks experts

View 10 Replies View Related

Stored Procedure - Too Many Rows Returned

Jan 12, 2007

The following query only brings back too much data in the table - there are duplicates and the lab it shows is wrong.
The problem is:  
AND a.calLab = f.ID
in the Where statement.
Some equipment does not need calibration, so, a.calDueDate = 0 AND a.calLab would be NULL or 0.
tblLabs ID field has 1 - 18 (Labs) - no 0 and of course no null
I need to get the rest of the data.
Any suggestions?
Thanks.....
Zath
 
SELECT a.assignedID,
b.Manufacturer,
a.modelNumber,
a.serialNumber,
e.equipmentType,
a.Description,
c.Location,
d.Status,
a.modifiedDate,
a.modifiedBy,
a.Notes,
a.Picture,
f.LabName,
a.calibrationRequired,
a.calDate,
a.CalDueDate,
a.assetNumber,
a.ID
FROM tblEquipments a,
tblManufacturers b,
tblLocation c,
tblStatus d,
tblEquipment_Type e,
tblLabs f
WHERE a.manufacturer = b.manufacturerID
AND a.location = c.locationID
AND a.Status = d.statusID
AND a.EquipmentType = e.ID
AND (a.calLab = f.ID or a.calLab Is NULL or a.calLab = 0)   
   ORDER BY a.ID
 
 

View 1 Replies View Related

Stored Procedure Returning No Rows

Mar 23, 2007

I have a stored procedure below that returns a table of coaches.  It worked before now it does not.  It returns nothing, in vistual studio 2005 and on my asp.net webpage.  But when I execute it in query analyzer with just SELECT * FROM Coaches it returns the rows.  There is no error just will not return what I need.  I recreated the database and stored procedure still doing the same thing.  Any ideas?  Would this be on my server hosting side? ALTER PROCEDURE [dbo].[GetCo]ASSELECT * FROM Coaches  

View 2 Replies View Related

Returning All Rows For A Stored Procedure

Mar 16, 2004

Hi,

I created a temporary table inside a stored procedure called TmpCursor and the last time I include this..

Select * from #TmpSummary
GO

Inside my web page, I have the following code...

QrySummary = "Exec TmpCursor"
Set rsSummary = Server.CreateObject("ADODB.RecordSet")
rsSummary.Open QrySummary, cnCentral

cnCentral is my sqlconnection string..


This is the error I got when viewing the page

Error Type:
ADODB.Recordset (0x800A0E78)
Operation is not allowed when the object is closed.

BTW, the stored procedure works fine in Query Analyzer.

TIA

View 2 Replies View Related

Stored Procedure Returning Too Few Rows

Feb 18, 2004

I can't even think how I would go about beginning to solve this problem, so any tips/pointers would help immensely.

I'm running a query that builds a time line of a process using messages in a table called Event. The Event table is joined with a table called Charge_Info based on N_Charge, the charge number. It builds the time line by looking in the Message field for various text strings that signify a specific point has been reached in the process and builds a record for each charge number with data from N_Charge and timestamps from the events table.

The problem I have is that there aren't records for every event in the Event table, ie, for every charge that doesn't have a "Heating Complete" event, the returned recordset has no mention of that charge. The system recording these events is pretty much crap, but there's nothing to be done about that right now. What I want to happen is for the query to return every record in N_Charge and a null string or NULL in place of the non-existing events.

The stored procedure is pasted below. I pass the dates I want and select from the Event table into a temporary table and then do the join/text search on that table. It helped performance tremendously compared to the text search searching all 400,000+ records in the Event table and then doing the date select.

Thanks for any help in advance,
TimC

SELECT EVENT.Time_Stamp, EVENT.N_CHARGE, EVENT.Message
INTO #EVENT_FILTERED
FROM EVENT
WHERE (EVENT.TIME_STAMP >= @StartDate) AND (EVENT.TIME_STAMP < @EndDate)

SELECT CHARGE_INFO.TIME_STAMP, CHARGE_INFO.N_CHARGE, CHARGE_INFO.BASE,
CHARGE_INFO.N_RECIPE, CHARGE_INFO.N_FCE, CHARGE_INFO.N_CH,
CHARGE_INFO.HEIGHT, CHARGE_INFO.CREW_EOC, CHARGE_INFO.CREW_SOC,
CHARGE_INFO.TIME_START, CHARGE_INFO.TIME_FCE_SET,
CHARGE_INFO.TIME_FCE_IGNITED, CHARGE_INFO.TIME_FCE_REMOVED,
CHARGE_INFO.TIME_CH_SET, CHARGE_INFO.TIME_CH_REMOVED,
CHARGE_INFO.WEIGHT, CHARGE_INFO.TIME_POST_PRG_COMPLETE,
EVENT.TIME_STAMP AS IC_Set,
EVENT_1.TIME_STAMP AS Cycle_Started,
EVENT_2.TIME_STAMP AS Leak_Test_Done,
EVENT_3.TIME_STAMP AS End_N2_PrePurge,
EVENT_4.TIME_STAMP AS Heating_Complete,
EVENT_5.TIME_STAMP AS Split_Temp_Met,
EVENT_6.TIME_STAMP AS End_N2_Final_Purge,
EVENT_7.TIME_STAMP AS Inner_Cover_Removed,
EVENT_8.TIME_STAMP AS Cycle_Complete,
EVENT_9.TIME_STAMP AS Post_Purge_Time_Met

FROM dbo.CHARGE_INFO CHARGE_INFO LEFT OUTER JOIN
#EVENT_FILTERED EVENT_9 ON CHARGE_INFO.N_CHARGE = EVENT_9.N_CHARGE LEFT OUTER JOIN
#EVENT_FILTERED EVENT_7 ON CHARGE_INFO.N_CHARGE = EVENT_7.N_CHARGE LEFT OUTER JOIN
#EVENT_FILTERED EVENT_6 ON CHARGE_INFO.N_CHARGE = EVENT_6.N_CHARGE LEFT OUTER JOIN
#EVENT_FILTERED EVENT_8 ON CHARGE_INFO.N_CHARGE = EVENT_8.N_CHARGE LEFT OUTER JOIN
#EVENT_FILTERED EVENT_5 ON CHARGE_INFO.N_CHARGE = EVENT_5.N_CHARGE LEFT OUTER JOIN
#EVENT_FILTERED EVENT_3 ON CHARGE_INFO.N_CHARGE = EVENT_3.N_CHARGE LEFT OUTER JOIN
#EVENT_FILTERED EVENT_1 ON CHARGE_INFO.N_CHARGE = EVENT_1.N_CHARGE LEFT OUTER JOIN
#EVENT_FILTERED EVENT_4 ON CHARGE_INFO.N_CHARGE = EVENT_4.N_CHARGE LEFT OUTER JOIN
#EVENT_FILTERED EVENT_2 ON CHARGE_INFO.N_CHARGE = EVENT_2.N_CHARGE LEFT OUTER JOIN
#EVENT_FILTERED EVENT ON CHARGE_INFO.N_CHARGE = EVENT.N_CHARGE

WHERE (EVENT.MESSAGE LIKE '%Inner Cover Set%') AND
(EVENT_1.MESSAGE LIKE '%Cycle Started%') AND
(EVENT_2.MESSAGE LIKE '%Leak Test Done%') AND
(EVENT_3.MESSAGE LIKE '%End of N2 PrePurge%') AND
(EVENT_4.MESSAGE LIKE '%Heating Complete%') AND
(EVENT_5.MESSAGE LIKE '%Split Temp Met%') AND
(EVENT_6.MESSAGE LIKE '%End N2 Final%') AND
(EVENT_7.MESSAGE LIKE '%Inner Cover Removed%') AND
(EVENT_8.MESSAGE LIKE '%Cycle Complete%') AND
(EVENT_9.MESSAGE LIKE '%Post Purge Time Met%') AND
(CHARGE_INFO.TIME_STAMP >= @StartDate) AND
(CHARGE_INFO.TIME_STAMP < @EndDate)

ORDER BY CHARGE_INFO.BASE, CHARGE_INFO.TIME_STAMP DESC

View 2 Replies View Related







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