Count Slowness Using CROSS APPLY

May 13, 2008



Hello,

I am doing a report that uses paging and in order to optimize it, i used row_number() so i could make it return x rows per page, so, in order to compute the number of pages needed, i have to count the total number of rows, which gets very slow because i'm using a cross apply with a table-valued function. Is there any way so i can get the number of rows processed by row_number() so i dont have the need to do count?

Thanks in advance !

View 3 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: String Occurrence Count With Cross Apply

Jun 17, 2014

See sample data below. I'm trying to count the number of occurrences of strings stored in table @word without a while loop.

DECLARE @t TABLE (Id INT IDENTITY(1,1), String VARCHAR(MAX))

INSERT INTO @t
SELECT 'There are a lot of Multidimensional Expressions (MDX) resources available' AS String UNION ALL
SELECT 'but most teaching aids out there are geared towards professionals with cube development experience' UNION ALL

[Code] .....

View 9 Replies View Related

CROSS APPLY Vs OUTER APPLY Example Messed Up?

Nov 27, 2007

Hi... I'm reading the MS Press 70-442 Self-Paced Training kit, and I'm having problems with this example.
I'd like help getting it to work correctly, or understand why it is isn't working the way I planned.

On page 67, the lab is about the APPLY operator (CROSS APPLY and OUTER APPLY). I first have to input a sample table-valued function into the AdventureWorks database:




Code Block
CREATE FUNCTION fnGetAvgCost(@ProdID int)
RETURNS @RetTable TABLE (AvgCost money)
AS
BEGIN
WITH Product(stdcost)
AS
(
SELECT avg(standardcost) as AvgCost
FROM Production.ProductCostHistory
WHERE ProductID = @ProdID
)
INSERT INTO @RetTable
SELECT * FROM Product
RETURN
END



and then run a sample T-SQL statement





Code Block
SELECT p.Name, p.ProductNumber,
Convert(varchar, cost.AvgCost,1) AS 'Average Cost'
FROM Production.Product p
CROSS APPLY fnGetAvgCost(p.ProductID) AS cost
WHERE cost.AvgCost IS NOT NULL
ORDER BY cost.AvgCost desc

My problem is with the WHERE clause... According to page 56, CROSS APPLY returns only rows from the outer table that produces a result set, so why do I need to explicitly filter NULL values?

When I remove the WHERE clause, the query retrieves lots of NULL AvgCost values.

Again, according to page 56, it is the OUTER APPLY that returns all rows that return a result set and will include NULL values in the columns that are returned from the table-valued function.

So, in short, I don't see the difference between CROSS APPLY and OUTER APPLY, using this example, when I remove the WHERE clause?

(Please refrain from introducing another example into this question.)

View 8 Replies View Related

Cross Apply

May 22, 2008

What is Cross Apply, when it will be used ?

View 2 Replies View Related

Cross Apply And Newid

Apr 28, 2008

Hi,

Why am I getting a different numbers of distinct ids in those queries?


USE AdventureWorks
go
Declare @myXml as xml
set @myXml = '
<lol>omg</lol>
<lol>rofl</lol>
';

select locations.*, T.c.value('.','nvarchar(max)') from
(
select newid() as Id
from Production.ProductModel
where ProductModelID in (7, 8)
) as locations cross apply @myXml.nodes('(/lol)') T(c);

select mytable.* , T.c.value('.','nvarchar(max)') from
(
select newid() as Id
union
select newid()
) as mytable cross apply @myXml.nodes('(/lol)') T(c);


Thanks,

Victor

View 8 Replies View Related

CROSS APPLY Equivalent

Apr 29, 2008

I have a question, is there any equivalent for the CROSS APPLY operator in SQL server 2000?



I have the following code in SQL Server 2005 and it works fine, but I need an equivalent code in SQL server 2000.





SELECT *

FROM Customers Cust CROSS APPLY dbo.GetAccountAttributes(Cust.AccountNo) Att





what I need is to join a function and passing it a dynamic parameter.



I need it urgently





Thanks in advance,

Imad Elayyan

View 1 Replies View Related

CROSS APPLY Equivalent

Apr 29, 2008



I have a question, is there any equivalent for the CROSS APPLY operator in SQL server 2000?

I have the following code in SQL Server 2005 and it works fine, but I need an equivalent code in SQL server 2000.



SELECT *

FROM Customers Cust CROSS APPLY dbo.GetAccountAttributes(Cust.AccountNo) Att



what I need is to join a function and passing it a dynamic parameter.

I need it urgently


Thanks in advance,
Imad Elayyan

View 6 Replies View Related

CROSS APPLY Sp_addextendedproperty

Nov 7, 2007

I am trying to add Extended properties to each of the columns in my table('MyTable')to the columns

DECLARE @NewTableName as nvarchar(128);

SET @NewTableName = 'MyTable'


SELECT ColumnName FROM(

SELECT c.name as ColumnName

FROM syscolumns c

INNER JOIN sysobjects o

ON o.id = c.id

WHERE o.name = @NewTableName) as T

OUTER APPLY

sp_addextendedproperty( 'Caption', ColumnName,





'user', 'dbo',

'table', @NewTableName,

'column', ColumnName)


I am getting an invalid object name 'sp_addextendedproperty' error.


Jaime

View 3 Replies View Related

Cross Apply And Newid

Apr 28, 2008

I've been trying to figure out why these two return a different amount of distinct ids...
Is that a bug in optimization?




Code Snippet


USE AdventureWorks
go
Declare @myXml as xml
set @myXml = '
<lol>omg</lol>
<lol>rofl</lol>
';

WITH locations as
(
select newid() as Id
from Production.ProductModel
where ProductModelID in (7, 8)
)
select locations.*, T.c.value('.','nvarchar(max)') from locations cross apply @myXml.nodes('(/lol)') T(c);

with mytable as
(
select newid() as Id
union
select newid()
)
select mytable.* , T.c.value('.','nvarchar(max)') from mytable cross apply @myXml.nodes('(/lol)') T(c);

View 4 Replies View Related

Multiple Cross Apply

Nov 14, 2006

Good Afternoon,

I'm attempting to leverage SQL's new 'APPLY" operator and I guess I don't fully understand it proper usage.

This is a relatively simple request, first i want to count the models produced within a valid period of time. The first 'Cross Apply' gets the valid starting and ending dates and looks ups the number of models produced for the period of time. This section of code works perfectly fine.

The problem appears to be with the second "Cross Apply".  What I'm attempting to accomplish is to count all models produced, regardless of time frame.

When executed the query appears to go into an loop and I end up canceling out the request.

Any ideas where I went wrong?? Any help is greatly appreciated!

 

select b1.model                            as Model 
      ,b1.MinDate                            as Mfg_Str_Date
      ,b1.MaxDate                           as Mfg_End_Date
      ,Count(b2.Model+B2.Serial) as Mfg_Date_Valid
      ,Count(b3.Model+B3.Serial) as All_Units

from        (select b.model, min(b.build_date) as MinDate ,max(b.build_date) as MaxDate
             from etbl_models_Serial as b
             group by b.model) as b1

--These are Units produced within Valid Window
cross apply (select b2.model,b2.Serial
             from etbl_Production as b2
             where b2.Model = b1.Model
               and b2.Mfg_Date between b1.MinDate and b1.MaxDate) as b2

--These are all units produced
cross apply (select b3.model,b3.Serial
             from etbl_Production as b3
             where b3.Model = b2.Model) as b3
      
Group by b1.Model, b1.MinDate, b1.MaxDate
Order by b1.Model

View 4 Replies View Related

Cross Apply Issue (Last Call) :)

May 28, 2008

I can't figure out what can be causing this.

When I use this query

Select top 1000 a.EmployeeID,b.*
from #TmpActiveEmployeesWSeverance a
cross apply
dbo.fn_Severance_AccountItemsTable(a.EmployeeID,a.BenefitTypeID,null,null,null,null) b
order by a.EmployeeID,a.BenefitTypeID


It runs 4 seconds

If I try to insert the results into anything It runs > 5 minutes (I have yet to let it finish)

I have tried the two following pieces of code, both with the same results


Select top 1000 a.EmployeeID,b.*
into #Tmp
from #TmpActiveEmployeesWSeverance a
cross apply
dbo.fn_Severance_AccountItemsTable(a.EmployeeID,a.BenefitTypeID,null,null,null,null) b
order by a.EmployeeID,a.BenefitTypeID

--and
Insert Into TRP_ActiveEmployeesWSeverance
(EmployeeID
,PK
,BeginningBalance
,BenefitInterestRowID
,BenefitInterestID
,BenefitTypeID
,DateReceived
,InvoiceDate
,Amount
,Hours
,Fraction1
,Fraction2
,Interest
,InterestAmount
,StartDate
,EndDate
,PeriodApplied
,Offset
,Reserve
,Account
,BenefitClosedID
,PaidOut
,ClosedAccount
,ai
,ClosedDate
,StartAgain
,PartialDividend
,PartialFraction
,SameDateCount)
Select top 1000 a.EmployeeID,b.*
from #TmpActiveEmployeesWSeverance a
cross apply
dbo.fn_Severance_AccountItemsTable(a.EmployeeID,a.BenefitTypeID,null,null,null,null) b
order by a.EmployeeID,a.BenefitTypeID


Any thoughts as to what can be disrupting this?

View 5 Replies View Related

Order Of Inner Joins And Cross Apply

Sep 29, 2015

Will the order of inner joins and cross apply effect the results of a query?

Example:
FROM dbo.vw_Info v
CROSS APPLY dbo.usf_LastFee(v.StoreID, v.AgreementID, v.CustomerID, ABS(v.PrePaymentBalance), cp.ConfirmationNo) lf
INNER JOIN dbo.Customers c

[Code] ....

I want to change the position of doing "CROSS APPLY". Will it effects query results?

View 2 Replies View Related

Error When Using XML Nodes As Cross Apply

Nov 12, 2012

 I have this query:

SELECT res.res_id,
sub.value('(./@id)[1]', 'char(2)') id
FROM vwResult res
CROSS APPLY report.nodes('/clue_personal_auto/report/search_dataset/subjects/*') report(sub)

It works just fine in SQL Query.After placing this into a view in SSDT November 2012 update, I get a compilation error.

View 11 Replies View Related

Using CROSS APPLY - Possibilities For Resolution

Apr 29, 2008



Hello,

is it possible to use CROSS APPLY like this:



SELECT [x]

FROM [Order] CROSS APPLY (SELECT .OrderNo + 3) [x]



i know you need [x].* but is it possible to use a function so that only [x] is needed?

thx in advance for help
MattGo

View 3 Replies View Related

Problem With Cross Apply Query

Nov 10, 2006

Hey guys. This is one of the queries pasted from BOL. I'm having problems excuting this query. The problem lies in the CROSS APPLY part. When I copy this query and run it in SSMS, it gives me an error saying 'Incorrect syntax near .' It doesn't like the qs.sql_handle part. If I remove that and pass the actual handle in for some query, it works. Can someone please tell me what I'm doing wrong?????? Also, I've sp1 installed on my SQL Server 2005 Enterprise, just in case if this matters. Below is the query pasted which is giving me problems. Thank you.

SELECT TOP 5 total_worker_time/execution_count AS [Avg CPU Time],

SUBSTRING(st.text, (qs.statement_start_offset/2)+1,

((CASE qs.statement_end_offset

WHEN -1 THEN DATALENGTH(st.text)

ELSE qs.statement_end_offset

END - qs.statement_start_offset)/2) + 1) AS statement_text

FROM sys.dm_exec_query_stats AS qs

CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st

ORDER BY total_worker_time/execution_count DESC;

View 3 Replies View Related

Transact SQL :: Replace Group By With CTE And / Or Cross Apply

Jul 10, 2015

If I Have a table like

Id(identity), PupilPersonId, EducationTypeId,VehicleTypeId,EducationDate, EducatorId,Canceled
661187       9242382         2                       1                2015-07-07 00:00:00.000 O_2 False
661183       9242382         2                       1            2015-07-08 00:00:00.000 O_2 False
661186       9242382         1                       1                2015-07-08 00:00:00.000 O_2 False
661178       9242382         2                       1                2015-07-10 00:00:00.000 O_2 False
661185       9242382         2                       1                2015-07-10 00:00:00.000 O_2 False

The result I want is the unique rows from columns:  

PupilPersonId, EducationTypeId,VehicleTypeId AND there MAX EducationDate
SELECT er1.* FROM EducationResult er1
INNER JOIN
(
SELECT
er.PupilPersonId, er.EducationTypeId, er.VehicleTypeId, MAX(er.EducationDate) as EducationDate

[Code] ....

I like to know is there another approach with CTE and or Cross Apply I can use instead?

View 5 Replies View Related

Find Nearest Date Record Without Cross Apply

Oct 13, 2012

Table :

ChangeID ChangeDate EquipmentID ModuleID EquipStatus
1 12/9/08 230 1789 Normal
2 13/9/08 450 1245 Normal
3 17/9/08 230 1789 Open
4 21/9/08 230 1899 Open
5 21/9/08 450 1674 Normal
6 22/9/08 450 2364 Normal

Given a date, what module was each equipment item in on that date?How do I get the date of the nearest previous event from a list like this? I got a query from one of the post in this Forum only using Cross Apply to find the nearest record from the above table based on Date i.e.

SELECT outerT.*
FROM your_table AS outerT
CROSS APPLY
(
SELECT TOP 1
equipment_id
, change_date
FROM your_table AS innerT
WHERE innerT.change_date <= @point_in_time
AND innerT.equipment_id = outerT.equipment_id
ORDER BY change_date DESC
) AS applicable_records
WHERE applicable_records.change_date = outerT.change_date

The problem is I need to get this query without using Cross Apply as i need to use the same for the LINQ which doesn't support Cross Apply.

View 1 Replies View Related

SQL Server 2012 :: Using Cross Apply To UNPIVOT Data

Jan 15, 2014

I was reading Kenneth Fisher's and Dwain Camps' articles on unpivoting using cross apply... And I can actually get them to work....

CREATE TABLE #TxCycle(
Cycle INT NOT NULL,
PatientID INT NOT NULL,
ALOPECIA TINYINT,
Causality1 TINYINT,
Relatedness1 TINYINT,

[Code] ....

The one thing I was wondering was this: how do I extract the symptom names from the field list without knowing them all beforehand? Dwain does this

-- DDL and sample data for UNPIVOT Example 2
CREATE TABLE #Suppliers
(ID INT, Product VARCHAR(500)
,Supplier1 VARCHAR(500), Supplier2 VARCHAR(500), Supplier3 VARCHAR(500)
,City1 VARCHAR(500), City2 VARCHAR(500), City3 VARCHAR(500))

Can this be adapted if you don't know all the column names beforehand? (Likely not). Back in the dark ages, when I was working on a database like this, it was in Access, and I could loop over the fields collection and evaluate each field name. (Yes, I know you're not supposed to store information in field names, but I inherited that mess!)

View 7 Replies View Related

SQL Server 2008 :: Cross Apply With Parameterized Function?

Sep 9, 2015

I'm unable to reproduce the error. when they upgrade their OS and SQL EXPRESS to a more recent version the error disappears.

The error is: Incorrect syntax near '.'

the query in question resembles this:

Select column1, column2
from Table1 T
cross apply function(t.column4,t.column5) F
where column3 = 'XXXX'

I made sure that the compatibility level is greater than 90 this error is happening on SQL2005 SP2 as well as SQL2008 with SP2 (but not all clients are suffering from the same problem)

Can it be the .net framework? Although the machines had .net framework 3.52.

Can the OS be an issue? The OS' seem to be old, Windows Server 2008 SP2

I've tried to reproduce the error by setting up virtual machines with same OS and SQL but, again, can't reproduce.

View 9 Replies View Related

T-SQL (SS2K8) :: How To Vary Column Names In Cross Apply Based On Different Columns In Each Table

Feb 26, 2015

I am using CROSS APPLY instead of UNPIVOT to unpivot > one column. I am wondering if I can dynamically replace column names based on different tables? The example code that I have working is based on the "Allergy" table. I have thirty more specialty tables to go. I'll show the working code first, then an example of another table's columns to show differences:

select [uplift specialty], [member po],[practice unit name], [final nomination status]
,[final uplift status], [final rank], [final uplift percentage]
,practiceID=row_number() over (partition by [practice unit name] order by Metricname)
,metricname,Metricvalue, metricpercentilerank

[code]....

Rheumatology Table:The columns that vary start with "GDR" and [GDR Percentile Rank] so I'm just showing those:

GDR (nvarchar(255), null)
GDR Percentile Rank (nvarchar(255), null)
GDR PGS (nvarchar(255), null)
GDR Rank Number (nvarchar(255), null)
PMPM (nvarchar(255), null)

[Code] ....

These are imported from an Excel Workbook so that's why all the columns with spaces for now.

View 9 Replies View Related

SQL Server 2012 :: CROSS APPLY Returning Records From Left Recordset Even When No Matching Record In Right One

Oct 7, 2014

Following is the query that I'm running:

create table a (id int, name varchar(10));
create table b(id int, sal int);
insert into a values(1,'John'),(1,'ken'),(2,'paul');
insert into b values(1,400),(1,500);

select *
from a
cross apply( select max(sal) as sal from b where b.id = a.id)b;

Below is the result for the same:

idname sal
1John500
1ken500
2paulNULL

Now I'm not sure why the record with ID 2 is coming using CROSS APPLY, shouldn't it be avoided in case of CROSS APPLY and only displayed when using OUTER APPLY.

One thing that I noticed was that if you remove the Aggregate function MAX then the record with ID 2 is not shown in the output. I'm running this query on SQL Server 2012.

View 6 Replies View Related

Dynamic SQL On Cross-Tab W/ Varying Col Count

Feb 25, 2008

Hi, I have this idea of using Dynamic SQL on a cross-tab and the following questions popped-up:

1) Is there a limit to the length of the statement the EXEC / sp_executesql command can execute?
2) Should I use cursors (Haven't used this one, I preferred work tables)?

Here are the details:

TABLE_SAMPLE
RptDate DATETIME,
SomeField CHAR(1),
ID CHAR(8),
RetVal VARCHAR(15)

SP Input:
A date range that defines what the RptDates are:
@DateFrom DATETIME,
@DateTo DATETIME

SP Output could be:

| SomeField | RptDate1 | RptDate2 | RptDate3 | RptDate4 | RptDate5 | RptDate..n
--------------------------------------------------------------------------------------------------
ID1 | A | RetVal1 | RetVal2 | RetVal3 | [BLANK] | RetVal5 | RetVal..n
ID2 | A | [BLANK] | ... | ... | ... | ... | ...
ID3 | C | [BLANK] | ... | [BLANK] | ... | ... | [BLANK]
ID..n | B | ... | ... | ... | ... | ... | RetVal..n

[BLANK] - means that there was no record for that RptDate for the ID

Conditions:
- The number of records per ID varies and depends on the number of RptDates covered by @DateFrom and @DateTo
ID1 can have records for 02/26/2008, 02/25/2008, 02/22/2008
ID2 can have records for one, two or all of the same dates.
etc...

Thanks.

View 5 Replies View Related

Subquery -&> Slowness

Feb 24, 2006

I have some queries that involve subqueries to select the appropriaterecord from a bunch of candidates. For example the following, whichselects the most recent transaction for a given customer:CREATE TABLE #Customer (CustID int, OtherInfo int)INSERT #Customer SELECT 1,7INSERT #Customer SELECT 2,8INSERT #Customer SELECT 3,9CREATE TABLE #Event (CustID int, EventID int, EventAmt int, EventDtsmalldatetime)INSERT #Event SELECT 1,1,1000,'20060224'INSERT #Event SELECT 2,1,2000,'20060224'INSERT #Event SELECT 3,2,3000,'20060224'INSERT #Event SELECT 3,1,5000,'20060225'SELECT c.CustID,c.OtherInfo ,e.EventAmt,e.EventDtFROM #Customer c JOIN #Event e ON c.CustID=e.CustIDWHERE EventDt = (SELECT MAX(EventDt) FROM #Event WHERE CustID=c.CustID)ORDER BY c.CustIDOver millions of customers and events, this takes forever. Creating atemp table which identifies the appropriate dates, and then joining tothat, speeds things up considerably -- the following two queriestogether take a lot less time the the one above.CREATE TABLE #Temp (CustID int,EventDt smalldatetime)INSERT #Temp SELECT CustID,MAX(EventDt)FROM #Event GROUP BY CustIDSELECT c.CustID,c.OtherInfo ,e.EventAmt,e.EventDtFROM #Customer cJOIN #Temp t ON t.CustID=c.CustIDJOIN #Event e ON c.CustID=e.CustID AND t.EventDt=e.EventDtThis seems pretty simple, and I would assume the query planner shouldbe able to figure it out without assistance. Is there a better way toforumulate the original query? BTW, as far as I can tell the indexesare appropriate for these queries; however the subqueries seem to bedone one at a time.

View 2 Replies View Related

SQL Server Slowness Problem

Sep 22, 2006

Any expert can tell me why the query I captured in profiler in the form below

declare @P1 int
set @P1=180150002
declare @P2 int
set @P2=1
declare @P3 int
set @P3=16388
declare @P4 int
set @P4=0
exec sp_cursoropen @P1 output, N'SELECT .... ', @P2 output, @P3 output, @P4 output
select @P1, @P2, @P3, @P4

is taken longer time if run using query analyzer? I tested the SELECT query in form above is only taken 26 seconds, whereas from profiler, it shown it tooks 3 minutes to run. My production server currently faced this slowness problem and hit timeout whenever the query is RPC from application.



-Tension

View 2 Replies View Related

Insert/ Update/ Delete Slowness.

Jul 10, 2006

SQL2K sp4

Howdy all. I opened a 200 mb. file in Query Analyzer that is full of Inserts/ Updates/ and Deletes. I tried just to parse it, and killed it after 18 hours. There is no blocking. All of the appropriate indexes exist. I even removed them and retried JIC. The box is plenty powerful for this task. Does anyone have any ideas?
I've tried several times with no luck. At the top of the file is SET IMPLICIT_TRANSACTIONS ON and then every 10,000 statements is COMMIT WORK. I've tried adjusting the number of commits to a lower number with no luck. This works fine on smaller files (3 - 20 mb).

View 1 Replies View Related

Slowness On Multi Processor Boxes.

Aug 16, 2006

SQL2K
SP4

Howdy all. I have a query with bizarre results in Query Analyzer.

Box1; 4 x 3.0 processors, 4 gigs of RAM. Results never come back.
Box2; 8 x 3.0 processors, 16 gigs of RAM. Results never come back.

Both of the above boxes are extremely under utilized. The absolute max amount of CPU being used is 25%. Box1 had 1 gig free RAM and Box2 had 7 gigs free RAM.

Box3; 1 x 3.0 processor, 1 gig of RAM. Results in 15 seconds.
Box4, all the same as box 3.

I took a backup of the DB and restored it from box to box to box, so I know everything is identical.

I once had a deadlock issue where I had to use the maxDop hint and tried that here, but it didn't help.

All ideas are appreciated.

TIA, cfr

View 1 Replies View Related

Slowness In SSIS Package And The Importance Of Disk Maintenance

Sep 22, 2006

During testing a package repetatively that deletes/inserts into several tables, over the course of several days, my package, which took 45 minutes to load 1700 XML files, began to take over 6 hours. Turns out it was an I/O bottleneck, and the Avg Disk Queue Length was around 200 and I was incurring many PAGEIOLATCH_EX. My devl machine uses a single local disk, no raid, so I had no options there, but I ran the maintenance wizard to recreate indexes/statistics and defraged the hard drive, and regained my original 45 minutes time. I guess I'll have to put a maintenance plan together to do this nightly.

-Kory

View 1 Replies View Related

Transaction Count After EXECUTE Indicates That A COMMIT Or ROLLBACK TRANSACTION Statement Is Missing. Previous Count = 1, Current Count = 0.

Aug 6, 2006

With the function below, I receive this error:Error:Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 1, current count = 0.Function:Public Shared Function DeleteMesssages(ByVal UserID As String, ByVal MessageIDs As List(Of String)) As Boolean        Dim bSuccess As Boolean        Dim MyConnection As SqlConnection = GetConnection()        Dim cmd As New SqlCommand("", MyConnection)        Dim i As Integer        Dim fBeginTransCalled As Boolean = False
        'messagetype 1 =internal messages        Try            '            ' Start transaction            '            MyConnection.Open()            cmd.CommandText = "BEGIN TRANSACTION"            cmd.ExecuteNonQuery()            fBeginTransCalled = True            Dim obj As Object            For i = 0 To MessageIDs.Count - 1                bSuccess = False                'delete userid-message reference                cmd.CommandText = "DELETE FROM tblUsersAndMessages WHERE MessageID=@MessageID AND UserID=@UserID"                cmd.Parameters.Add(New SqlParameter("@UserID", UserID))                cmd.Parameters.Add(New SqlParameter("@MessageID", MessageIDs(i).ToString))                cmd.ExecuteNonQuery()                'then delete the message itself if no other user has a reference                cmd.CommandText = "SELECT COUNT(*) FROM tblUsersAndMessages WHERE MessageID=@MessageID1"                cmd.Parameters.Add(New SqlParameter("@MessageID1", MessageIDs(i).ToString))                obj = cmd.ExecuteScalar                If ((Not (obj) Is Nothing) _                AndAlso ((TypeOf (obj) Is Integer) _                AndAlso (CType(obj, Integer) > 0))) Then                    'more references exist so do not delete message                Else                    'this is the only reference to the message so delete it permanently                    cmd.CommandText = "DELETE FROM tblMessages WHERE MessageID=@MessageID2"                    cmd.Parameters.Add(New SqlParameter("@MessageID2", MessageIDs(i).ToString))                    cmd.ExecuteNonQuery()                End If            Next i
            '            ' End transaction            '            cmd.CommandText = "COMMIT TRANSACTION"            cmd.ExecuteNonQuery()            bSuccess = True            fBeginTransCalled = False        Catch ex As Exception            'LOG ERROR            GlobalFunctions.ReportError("MessageDAL:DeleteMessages", ex.Message)        Finally            If fBeginTransCalled Then                Try                    cmd = New SqlCommand("ROLLBACK TRANSACTION", MyConnection)                    cmd.ExecuteNonQuery()                Catch e As System.Exception                End Try            End If            MyConnection.Close()        End Try        Return bSuccess    End Function

View 5 Replies View Related

Analysis :: Count Function Taking More Time To Get Count From Parent Child Dimension?

May 25, 2015

below data,

Countery
parentid
CustomerSkId
sales

A
29097
29097
10

A
29465
29465
30

A
30492
30492
40

[code]....
 
Output

Countery
parentCount

A
8

B
3

c
3

in my count function,my code look like,

 set buyerset as exists(dimcustomer.leval02.allmembers,custoertypeisRetailers,"Sales")
set saleset(buyerset)
set custdimensionfilter as {custdimensionmemb1,custdimensionmemb2,custdimensionmemb3,custdimensionmemb4}
set finalset as exists(salest,custdimensionfilter,"Sales")
Set ProdIP as dimproduct.dimproduct.prod1
set Othersset as (cyears,ProdIP)
(exists(([FINALSET],Othersset,dimension2.dimension2.item3),[DimCustomerBuyer].[ParentPostalCode].currentmember, "factsales")).count

it will take 12 to 15 min to execute.

View 3 Replies View Related

How To Apply Hot Fix?

Mar 26, 2007

I have a sql server problem for which the solution is at,

http://support.microsoft.com/kb/889521

The article talks about a hot fix, but there is no link for download the hot fix.

Can anyone have a look and guide me.

Thanks



------------------------
I think, therefore I am - Rene Descartes

View 4 Replies View Related

Does SETROWCOUNT 10 Apply To Only The Sp In Which It Used Or Outside It Also?

May 23, 2007

I am using SETROWCOUNT 10 in my stored procedure. At end of thi sp I use SETROWCOUNT 0.
Will all other sp's that are executing at the same time as the above sp, get affected by the above SETROWCOUNT statement?

View 1 Replies View Related

Using Like And Apply To 3 Columns

Sep 7, 2007

 I have a table called Courses with columns "courseCode" "courseName" and "TeacherName"Im passing in a value @prefixText ...I have the following...Select courseModuleCode from courses Where courseModuleCode like @prefixTextwhat I actually want to do is return one list, i.e. one column that will do the same for  "courseName" and "TeacherName" aswell based on what the @prefix tag is...so i will end up with one column that may contains some or all of the following courseModuleCode, courseName, TeacherName. Im basically implementing a search on this table and want the users to search by any of the column nameshope this makes sense.   

View 6 Replies View Related

DTS Globalvariable Not Apply ......

Jun 24, 2004

I am new to DTS.
In ExecuteSQLTask:
want the original sql statement of <<backup database databaeABC to backup_databaseABC with init>> to be

backup database ? to 'backup_' + ? with init

But it looks the parameter could not place a globalVariable to it and parse it with error.
One alternate way probably need to create a proc to pass a parm to it....

Also, how could pass a globalVariable to a FTP task?

thanks
-D

View 4 Replies View Related







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